A consistent way to get native window handles (HWND)

In the full desktop framework all Controls and Forms expose the Handle property which
represents the native window handle of the control – this can be passed to API functions.
In the Compact Framework this property is not implemented. In the Smart
Device Framework
 we have created the OpenNETCF.Windows.Forms.IWin32Window interface
which matches the equivalent interface on the full framework. You can implement this
interface in your custom controls and forms to provide a standard way of exposing
the window handle.

Getting the handle to any control requires just one P/Invoked API function – GetCapture
which returns the window handle of the control with capture (able to receive mouse/stylus
input). First Capture is set on the control, then this API call will return the HWND
of the control, finally capture is optionally release from the control. The GetCapture
function is implemented in the OpenNETCF.Win32.Win32Window class,
or you can P/Invoke it directly. The following code illustrates adding IWin32Window
support to your control:-


Imports OpenNETCF.Windows.Forms
Imports OpenNETCF.Win32

Public Class MyControl
    Inherits System.Windows.Forms.Control
    Implements IWin32Window

    Overridable ReadOnly Property Handle() As System.IntPtr
            Me.Capture = True

            Dim thishandle As IntPtr
            thishandle = Win32Window.GetCapture()
            Me.Capture = False
            Handle = thishandle
        End Get
    End Property
End Class


using OpenNETCF.Windows.Forms;
using OpenNETCF.Win32;

public class MyControl : Control, IWin32Window
   public IntPtr Handle
           this.Capture = true;
           IntPtr thishandle = Win32Window.GetCapture();
           this.Capture = false;
           return thishandle;

By using the Interface approach rather than adding in support for handles on an ad-hoc
basis you have a garunteed signature for your handle implementation. Therefore
if you have a method which requires a native window handle you can accept an IWin32Window
as an argument. We will be ensuring that all our OpenNETCF controls in the future
implement this interface so you can rely on the Handle property to get the native
window handle.