Control.CreateGraphics 方法

定義

建立控制項的 Graphics

C#
public System.Drawing.Graphics CreateGraphics();

傳回

控制項的 Graphics

範例

下列程式碼範例會調整指定的控制項大小,讓控制項容納其格式化的文字。 格式化的文字是 Text 已套 Font 用至文字之控制項的 屬性。 AutoSizeControl此範例中的 方法也有參數 textPadding ,表示要套用至控制項所有邊緣的邊框間距。 若要讓邊框間距看起來相等,請在控制項支援時,將文字與 MiddleCenter 的值 System.Drawing.ContentAlignment 對齊。

C#
private void AutoSizeControl(Control control, int textPadding)
{
   // Create a Graphics object for the Control.
   Graphics g = control.CreateGraphics();

   // Get the Size needed to accommodate the formatted Text.
   Size preferredSize = g.MeasureString(
      control.Text, control.Font).ToSize();

   // Pad the text and resize the control.
   control.ClientSize = new Size(
      preferredSize.Width + (textPadding * 2), 
      preferredSize.Height+(textPadding * 2) );

   // Clean up the Graphics object.
   g.Dispose();
}

備註

Graphics您透過 CreateGraphics 方法擷取的物件通常不應該在處理目前的 Windows 訊息之後保留,因為使用該物件繪製的任何專案都會被下一個WM_PAINT訊息清除。 因此,您無法快取 Graphics 物件以供重複使用,除非使用非視覺方法,例如 Graphics.MeasureString 。 相反地,您必須在每次想要使用 Graphics 物件時呼叫 CreateGraphics ,然後在完成使用時呼叫 Dispose 。 如需 Windows 訊息的詳細資訊,請參閱 WndProc

根據設計, CreateGraphics 將擁有權設定為呼叫執行緒,並在其他執行緒上呼叫時失敗。

注意

除了 屬性之外 InvokeRequired ,控制項上還有四個安全線程的方法: Invoke 、、 BeginInvokeEndInvokeCreateGraphics 如果已經建立控制項的控制碼。 在背景執行緒上建立控制項控制碼之前呼叫 CreateGraphics ,可能會導致不合法的跨執行緒呼叫。 對於所有其他方法呼叫,您應該使用其中一個叫用方法來封送處理控制項執行緒的呼叫。

適用於

產品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另請參閱