Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

NativeWindow Class

Provides a low-level encapsulation of a window handle and a window procedure.


Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

[SecurityPermissionAttribute(SecurityAction::LinkDemand, Flags = SecurityPermissionFlag::UnmanagedCode)]
[SecurityPermissionAttribute(SecurityAction::InheritanceDemand, Flags = SecurityPermissionFlag::UnmanagedCode)]
public ref class NativeWindow : public MarshalByRefObject, 

The NativeWindow type exposes the following members.

Public methodNativeWindowInitializes an instance of the NativeWindow class.

Public propertyHandleGets the handle for this window.

Public methodAssignHandleAssigns a handle to this window.
Public methodCreateHandleCreates a window and its handle with the specified creation parameters.
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodDefWndProcInvokes the default window procedure associated with this window.
Public methodDestroyHandleDestroys the window and its handle.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeReleases the resources associated with this window. (Overrides Object::Finalize().)
Public methodStatic memberFromHandleRetrieves the window associated with the specified handle.
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodMemberwiseClone()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected methodOnHandleChangeSpecifies a notification method that is called when the handle for a window is changed.
Protected methodOnThreadExceptionWhen overridden in a derived class, manages an unhandled thread exception.
Public methodReleaseHandleReleases the handle associated with this window.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Protected methodWndProcInvokes the default window procedure associated with this window.

This class automatically manages window class creation and registration.

A window is not eligible for garbage collection when it is associated with a window handle. To ensure proper garbage collection, handles must either be destroyed manually using DestroyHandle or released using ReleaseHandle.


The ReleaseHandle method is called when the WM_NCDESTROY message is processed. This means there are cases in which when you do not need to manually call ReleaseHandle, but it is good practice to do so.

The NativeWindow class provides the following properties and methods to manage handles: Handle, CreateHandle, AssignHandle, DestroyHandle, and ReleaseHandle.

The following code example demonstrates intercepting operating system window messages in a window procedure, and creating a window with a specific operating system window class name. The example creates two classes that inherit from NativeWindow that accomplish this.

The MyNativeWindowListener class hooks into the window procedure of the form passed into the constructor, and overrides the WndProc method to intercept the WM_ACTIVATEAPP window message. The class demonstrates the usage of the AssignHandle and ReleaseHandle methods to identify the window handle the NativeWindow will use. The handle is assign based upon the Control::HandleCreated and Control::HandleDestroyed events. When the WM_ACTIVATEAPP window message is received, the class calls the form1 ApplicationActivated method.

The MyNativeWindow class creates a new window with the ClassName set to BUTTON. The class demonstrates using the CreateHandle method and overriding the WndProc method to intercept window messages that are received.

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System::Runtime::InteropServices;
ref class MyNativeWindowListener;
ref class MyNativeWindow;

// Summary description for Form1.
ref class Form1: public System::Windows::Forms::Form
   MyNativeWindowListener^ nwl;
   MyNativeWindow^ nw;

   void ApplicationActived( bool ApplicationActivated )
      // The application has been activated or deactivated
      #if defined(DEBUG)
      System::Diagnostics::Debug::WriteLine( "Application Active = {0}", ApplicationActivated.ToString() );


// NativeWindow class to listen to operating system messages.
ref class MyNativeWindowListener: public NativeWindow

   // Constant value was found in the S"windows.h" header file.
   literal int WM_ACTIVATEAPP = 0x001C;
   Form1^ parent;

   MyNativeWindowListener( Form1^ parent )
      parent->HandleCreated += gcnew EventHandler( this, &MyNativeWindowListener::OnHandleCreated );
      parent->HandleDestroyed += gcnew EventHandler( this, &MyNativeWindowListener::OnHandleDestroyed );
      this->parent = parent;


   // Listen for the control's window creation and then hook into it.
   void OnHandleCreated( Object^ sender, EventArgs^ /*e*/ )
      // Window is now created, assign handle to NativeWindow.
      AssignHandle( (dynamic_cast<Form1^>(sender))->Handle );

   void OnHandleDestroyed( Object^ /*sender*/, EventArgs^ /*e*/ )
      // Window was destroyed, release hook.


   virtual void WndProc( Message %m ) override
      // Listen for operating system messages
      switch ( m.Msg )
         case WM_ACTIVATEAPP:

            // Notify the form that this message was received.
            // Application is activated or deactivated,
            // based upon the WParam parameter.
            parent->ApplicationActived( ((int)m.WParam != 0) );
      NativeWindow::WndProc( m );


// MyNativeWindow class to create a window given a class name.
ref class MyNativeWindow: public NativeWindow

   // Constant values were found in the S"windows.h" header file.
   literal int WS_CHILD = 0x40000000,WS_VISIBLE = 0x10000000,WM_ACTIVATEAPP = 0x001C;
   int windowHandle;

   MyNativeWindow( Form^ parent )
      CreateParams^ cp = gcnew CreateParams;

      // Fill in the CreateParams details.
      cp->Caption = "Click here";
      cp->ClassName = "Button";

      // Set the position on the form
      cp->X = 100;
      cp->Y = 100;
      cp->Height = 100;
      cp->Width = 100;

      // Specify the form as the parent.
      cp->Parent = parent->Handle;

      // Create as a child of the specified parent
      cp->Style = WS_CHILD | WS_VISIBLE;

      // Create the actual window
      this->CreateHandle( cp );


   // Listen to when the handle changes to keep the variable in sync

   virtual void OnHandleChange() override
      windowHandle = (int)this->Handle;

   virtual void WndProc( Message % m ) override
      // Listen for messages that are sent to the button window. Some messages are sent
      // to the parent window instead of the button's window.
      switch ( m.Msg )
         case WM_ACTIVATEAPP:

            // Do something here in response to messages
      NativeWindow::WndProc( m );

   this->Size = System::Drawing::Size( 300, 300 );
   this->Text = "Form1";
   nwl = gcnew MyNativeWindowListener( this );
   nw = gcnew MyNativeWindow( this );

// The main entry point for the application.

int main()
   Application::Run( gcnew Form1 );

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Community Additions

© 2015 Microsoft