C# WinForm控制元件及其子控制元件轉成圖片(支援帶捲軸的長截圖)

tpen發表於2024-05-29
  • 概述(Overview)

參考了網上的分享,感覺都不太理想:1.一個控制元件內如果包含多個子控制元件時沒有考慮順序問題;2.超出控制元件可顯示區域時不能長截圖,有捲軸會多餘擷取了捲軸。這個隨筆旨在解決這個問題,實現帶捲軸時可以長截圖,並且給出了在多個子控制元件的情況下如何控制截圖順序的程式碼。有用可以點個贊。引用本文章請註明出處,謝謝。

(Referring to the Share on the Internet, I feel that it is not ideal: 1. If there are multiple sub-controls in a control, the order is not considered; 2. When the display area of the control is exceeded, the screenshot cannot be long, and the scroll bar will be redundantly intercepted. This essay aims to solve this problem by implementing long screenshots with scrollbars, and gives code on how to control the order of screenshots in the case of multiple child controls. If it's useful, you can like it. Please indicate the source for citing this article, thank you.)

C# WinForm控制元件及其子控制元件轉成圖片(支援帶捲軸的長截圖)
 1         /// <summary>
 2         /// 繪製整個控制元件以及子控制元件
 3         /// </summary>
 4         /// <param name="ctrl">視窗/控制元件</param>
 5         /// <param name="bitmap">bit圖片</param>
 6         /// <returns></returns>
 7         private Bitmap DrawToBitmap(Control ctrl, Bitmap bitmap = null)
 8         {
 9             //獲取整個介面的大小
10             var w = ctrl.DisplayRectangle.Width;
11             var h = ctrl.DisplayRectangle.Height;
12 
13             //長截圖
14             if (bitmap == null)
15             {
16                 bitmap = ctrl.BackgroundImage == null ? new Bitmap(w, h) : new Bitmap(ctrl.BackgroundImage);
17             }
18 
19             if (ctrl.HasChildren)
20             {
21                 //繪製子控制元件內容(逆序處理:圖層從下開始往上疊取)
22                 for (int i = ctrl.Controls.Count - 1; i >= 0; i--)
23                 {
24                     var control = ctrl.Controls[i];
25                     //重新計算圖片在bitmap上的位置
26                     var newLocation = new Point(control.Location.X - ctrl.DisplayRectangle.X, control.Location.Y - ctrl.DisplayRectangle.Y);
27 
28                     using (Bitmap temp = new Bitmap(control.Width, control.Height))
29                     using (Graphics g = Graphics.FromImage(bitmap))
30                     {
31                         control.DrawToBitmap(temp, new Rectangle(new Point(0, 0), control.Size));
32                         g.DrawImage(temp, new Rectangle(newLocation, control.Size));
33                     }
34                     DrawToBitmap(control, bitmap);
35                 }
36             }
37 
38             return bitmap;
39         }
Code

  • 引用(Reference)

  • c#將某個控制元件或整個窗體匯出為圖片_c# 控制元件轉圖片-CSDN部落格
  • C# 擷取控制元件圖,有滾動截圖功能 - 夢想(胡大利) - 部落格園 (cnblogs.com)

相關文章