WPF 复制粘贴到系统粘贴板

复制或剪切文件到剪切板

/// 
        /// 复制或剪切文件到剪切板
        /// 
        /// 文件路径数组
        /// true:剪切;false:复制
        public static void CopyToClipboard(string[] files, bool cut)
        {
            if (files == null) return;
            IDataObject data = new DataObject(DataFormats.FileDrop, files);
            MemoryStream memo = new MemoryStream(4);
            byte[] bytes = new byte[] { (byte)(cut?2:5),0,0,0};
            memo.Write(bytes,0,bytes.Length);
            data.SetData("PreferredDropEffect",memo);
            Clipboard.SetDataObject(data,false);
        }

复制文本

  private void La_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            StackPanel st = e.Source as StackPanel;
            StringBuilder Copystr = new StringBuilder();
            foreach (TextBox tb in GetChildObjects(st))
            {
                Copystr.Append(" ");
                Copystr.Append(tb.Text);
                SolidColorBrush myBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0xad, 0xd6, 0xff));
                tb.Background = myBrush;
            }
            Clipboard.SetText(Copystr.ToString());
            MessageToolTip.Show("数据复制成功");
        }

保存图片

// UI --> Png
public static void UISaveToPng(this FrameworkElement ui, string fileName)
{
    int width = (int)ui.ActualWidth;
    int height = (int)ui.ActualHeight;
    RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32);
    bmp.Render(ui);
    PngBitmapEncoder encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bmp));
    FileStream fs = new FileStream(fileName, FileMode.Create);
    encoder.Save(fs);
    fs.Close();
}

转BitmapImage

int width = (int)grid2DMap.ActualWidth;
int height = (int)grid2DMap.ActualHeight;
RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32);
bmp.Render(grid2DMap);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
BitmapImage bitmapImage = new BitmapImage();
using (var memoryStream = new MemoryStream())
{
    encoder.Save(memoryStream);
    memoryStream.Seek(0, SeekOrigin.Begin);
    bitmapImage.BeginInit();
    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.StreamSource = memoryStream;
    bitmapImage.EndInit();
}

转System.Drawing.Image

MemoryStream memoryStream = new MemoryStream();
encoder.Save(memoryStream);
System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream);

你可能感兴趣的:(wpf,c#)