Control.CreateGraphics 方法

定义

为控件创建 Graphics

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

返回

Graphics

控件的 Graphics

示例

下面的代码示例调整指定控件的大小,以便控件容纳其格式化文本。 带格式的文本是 Text 控件分配给 Font 文本的属性。 AutoSizeControl此示例中的方法还具有一个textPadding参数,该参数表示要应用于控件的所有边缘的填充。 若要使填充显示相等,请将文本与MiddleCenterSystem.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处理当前 Windows 消息后,通常不应保留通过CreateGraphics该方法检索的对象,因为用该对象绘制的任何内容都将用下一条WM_PAINT消息擦除。 因此,不能缓存 Graphics 对象以供重复使用,除非使用非视觉方法,例如 Graphics.MeasureString。 相反,每次想要使用该Graphics对象时都必须调用CreateGraphics,然后在使用完对象时调用Dispose。 有关 Windows 消息的详细信息,请参阅 WndProc

根据设计, CreateGraphics 将所有权设置为调用线程,并在其他线程上调用该线程时失败。

备注

除了 InvokeRequired 属性之外,控件上还有四种方法是线程安全的: InvokeBeginInvokeEndInvoke以及 CreateGraphics 控件的句柄是否已创建。 在后台线程上创建控件句柄之前调用 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
Windows Desktop 3.0, 3.1, 5, 6, 7

另请参阅