Edit

Share via


NativeWindow Class

Definition

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

C#
public class NativeWindow : MarshalByRefObject
C#
public class NativeWindow : MarshalByRefObject, System.Windows.Forms.IWin32Window
Inheritance
NativeWindow
Implements

Examples

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.

C#
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace NativeWindowApplication
{
    // Summary description for Form1.
    public class Form1 : System.Windows.Forms.Form
    {
        private MyNativeWindowListener nwl;
        private MyNativeWindow nw;

        internal void ApplicationActivated(bool ApplicationActivated)
        {
            // The application has been activated or deactivated
            System.Diagnostics.Debug.WriteLine("Application Active = " + ApplicationActivated.ToString());
        }

        private Form1()
        {
            this.Size = new System.Drawing.Size(300, 300);
            this.Text = "Form1";

            nwl = new MyNativeWindowListener(this);
            nw = new MyNativeWindow(this);
        }

        // The main entry point for the application.
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }
    }

    // NativeWindow class to listen to operating system messages.
    internal class MyNativeWindowListener : NativeWindow
    {
        // Constant value was found in the "windows.h" header file.
        private const int WM_ACTIVATEAPP = 0x001C;

        private Form1 parent;

        public MyNativeWindowListener(Form1 parent)
        {

            parent.HandleCreated += new EventHandler(this.OnHandleCreated);
            parent.HandleDestroyed += new EventHandler(this.OnHandleDestroyed);
            this.parent = parent;
        }

        // Listen for the control's window creation and then hook into it.
        internal void OnHandleCreated(object sender, EventArgs e)
        {
            // Window is now created, assign handle to NativeWindow.
            AssignHandle(((Form1)sender).Handle);
        }
        internal void OnHandleDestroyed(object sender, EventArgs e)
        {
            // Window was destroyed, release hook.
            ReleaseHandle();
        }

        protected override void WndProc(ref Message m)
        {
            // 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.ApplicationActivated(((int)m.WParam != 0));

                    break;
            }
            base.WndProc(ref m);
        }
    }

    // MyNativeWindow class to create a window given a class name.
    internal class MyNativeWindow : NativeWindow
    {

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

        private int windowHandle;

        public MyNativeWindow(Form parent)
        {

            CreateParams cp = new 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
        protected override void OnHandleChange()
        {
            windowHandle = (int)this.Handle;
        }

        protected override void WndProc(ref Message m)
        {
            // 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
                    break;
            }
            base.WndProc(ref m);
        }
    }
}

Remarks

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.

Note

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.

Constructors

NativeWindow()

Initializes an instance of the NativeWindow class.

Properties

Handle

Gets the handle for this window.

Methods

AssignHandle(IntPtr)

Assigns a handle to this window.

CreateHandle(CreateParams)

Creates a window and its handle with the specified creation parameters.

CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
DefWndProc(Message)

Invokes the default window procedure associated with this window.

DestroyHandle()

Destroys the window and its handle.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize()

Releases the resources associated with this window.

FromHandle(IntPtr)

Retrieves the window associated with the specified handle.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
OnHandleChange()

Specifies a notification method that is called when the handle for a window is changed.

OnThreadException(Exception)

When overridden in a derived class, manages an unhandled thread exception.

ReleaseHandle()

Releases the handle associated with this window.

ToString()

Returns a string that represents the current object.

(Inherited from Object)
WmDpiChangedAfterParent(Message)
WmDpiChangedBeforeParent(Message)
WndProc(Message)

Invokes the default window procedure associated with this window.

Applies to

Product Versions
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

See also