简体   繁体   中英

How to get handle of current control in user-defined control class

I want to retrieve update rectangle in a user-defined panel's OnPaint method, but the handle of this panel is needed. I wander how to get handle of current control. The code is as follow:

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
  }
}

Easy solution (since MyPanel has been inherired from Control which has HWND ):

 protected override void OnPaint(PaintEventArgs e) {
   ...
   // Panel is inherited from Control which has HWND
   IntPtr hWnd = this.Handle;
 }

Complex, but general case solution ( MyPanel can be any class, not necessarily a Control ):

 [DllImport("User32.dll")]
 private static extern IntPtr WindowFromDC(IntPtr hDC);

 // override: depending on MyClass it can be protected virtual void...
 protected override void OnPaint(PaintEventArgs e) {
   ...
   IntPtr hDC = e.Graphics.GetHdc();

   try {
     IntPtr hWnd = WindowFromDC(hDC);
     ...
   }
   finally {
     e.Graphics.ReleaseHdc(hDC);
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM