1. 程式人生 > >C#實戰小技巧(八):將剪下板中的內容儲存為圖片

C#實戰小技巧(八):將剪下板中的內容儲存為圖片

進行C#開發時,可以將複製到剪下板中的內容轉為HTML檔案,再將HTML頁面轉為圖片進行儲存,示例效果如下。
被複制的Excel表格:
這裡寫圖片描述
生成的圖片:
這裡寫圖片描述
實現上述功能的主要程式碼如下,能夠將從Word、Excel、網頁等地方複製的內容匯出,並儲存為圖片。
程式碼:

        public MainWindow()
        {
            InitializeComponent();
            // 載入鍵盤監聽事件
            this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
        }

        // C#內建瀏覽器物件
private System.Windows.Forms.WebBrowser webBrowser; /// <summary> /// 監聽鍵盤按鍵事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainWindow_KeyDown(object sender, KeyEventArgs e) { //同時按下了Ctrl + V鍵(V要最後按,因為判斷了此次事件的e.Key)
//修飾鍵只能按下Ctrl,如果還同時按下了其他修飾鍵,則不會進入 if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.V) { if (Clipboard.ContainsData(DataFormats.Html)) { //將剪下板中的內容先轉為HTML,再轉成圖片 string
html = Clipboard.GetData(DataFormats.Html).ToString(); //去除HTML檔案中的檔案源資訊部分 html = html.Substring(html.IndexOf("<html")); webBrowser = new System.Windows.Forms.WebBrowser(); //是否顯式滾動條 webBrowser.ScrollBarsEnabled = false; //載入 html webBrowser.DocumentText = html; //頁面載入完成執行事件 webBrowser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted); } } } /// <summary> /// 表格html載入完畢事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void webBrowser_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e) { //獲取解析後HTML的大小 System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle; int width = rectangle.Width; int height = rectangle.Height; //設定解析後HTML的可視區域 webBrowser.Width = width; webBrowser.Height = height; string filePath = string.Empty; using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height)) { webBrowser.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, width, height)); //設定圖片檔案儲存路徑和圖片格式,格式可以自定義 string dir = new StringBuilder(AppDomain.CurrentDomain.BaseDirectory).Append(ICTResources.ICTUser.Session.useraccount).Append("\\Image").ToString(); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } filePath = new StringBuilder(dir).Append("\\").Append(DateTime.Now.ToString("yyyyMMddHHmmss.")).Append("png").ToString(); bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png); } if (File.Exists(filePath)) { messageMethods.SendChosenPicture(filePath); } }