進行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);
}
}