2017-04-17 64 views
1

我想要檢索的用戶自定義面板的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 
    } 
} 
+0

'IntPtr hWnd = this.Handle;'? –

+0

也許[this.Handle](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.handle(v = vs.110).aspx)? –

+0

謝謝你的回答! – proshm

回答

0

簡單的解決方案(因爲MyPanel已從Control具有HWND inherired):

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

複雜,但一般情況下溶液(MyPanel可以是任何類別,而不是必然 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); 
    } 
} 
相關問題