如何在用户定义的控件类中处理当前控件

时间:2017-04-17 09:46:46

标签: c#

我想在用户定义的面板OnPaint方法中检索更新矩形,但需要此面板句柄。我徘徊如何获得当前控件的句柄。代码如下:

class MyPanel : Panel
{
  [DllImport("User32.dll")]
  public static extern bool GetUpdateRect(IntPtr hWnd, out Rectangle lpRect, bool bErase);

  protected override void OnPaint(PaintEventArgs e)
  {
    Rectangle updateRect;
    IntPtr hWnd = IntPtr.Zero;
    // hWnd = ?; I wonder how to get handle of this panel
    GetUpdateRect(hWnd, out updateRect, false);

    base.OnPaint(e);
    // following drawing code is omited
  }
}

1 个答案:

答案 0 :(得分:0)

简易解决方案(因为<form method="GET" action="."></form>已从MyPanel继承而来Control):

HWND

复杂,但一般情况解决方案( protected override void OnPaint(PaintEventArgs e) { ... // Panel is inherited from Control which has HWND IntPtr hWnd = this.Handle; } 可以是任何类,而不是必然 a MyPanel) :

Control