共用方式為


NativeWindow 類別

定義

提供視窗控制代碼 (Window Handle) 和視窗程序 (Window Procedure) 的低階封裝。

public ref class NativeWindow : MarshalByRefObject
public ref class NativeWindow : MarshalByRefObject, System::Windows::Forms::IWin32Window
public class NativeWindow : MarshalByRefObject
public class NativeWindow : MarshalByRefObject, System.Windows.Forms.IWin32Window
type NativeWindow = class
    inherit MarshalByRefObject
type NativeWindow = class
    inherit MarshalByRefObject
    interface IWin32Window
Public Class NativeWindow
Inherits MarshalByRefObject
Public Class NativeWindow
Inherits MarshalByRefObject
Implements IWin32Window
繼承
NativeWindow
實作

範例

下列程式碼範例示範在視窗程式中攔截作業系統視窗訊息,以及建立具有特定作業系統視窗類別名稱的視窗。 此範例會建立兩個繼承自 NativeWindow 的類別來完成這項作業。

類別 MyNativeWindowListener 會連結至傳遞至建構函式之表單的視窗過程,並覆寫 WndProc 方法來攔截 WM_ACTIVATEAPP 視窗訊息。 類別示範 和 方法的使用 AssignHandle 方式,以識別 將使用的視窗控制碼 NativeWindowReleaseHandle 控制碼會根據 Control.HandleCreatedControl.HandleDestroyed 事件指派。 WM_ACTIVATEAPP收到視窗訊息時,類別會呼叫 form1.ApplicationActivated 方法。

類別 MyNativeWindow 會建立新的視窗,並將 ClassName 設定為 BUTTON 。 類別示範如何使用 CreateHandle 方法,並覆寫 WndProc 方法來攔截收到的視窗訊息。

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
{
private:
   MyNativeWindowListener^ nwl;
   MyNativeWindow^ nw;

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


public:
   Form1();
};

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

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

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

internal:

   // 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.
      ReleaseHandle();
   }

protected:

   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) );
            break;
      }
      NativeWindow::WndProc( m );
   }

};

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

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

public:
   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 );
   }

protected:

   // 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
            break;
      }
      NativeWindow::WndProc( m );
   }
};

Form1::Form1()
{
   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.

[STAThread]
int main()
{
   Application::Run( gcnew Form1 );
}
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);
        }
    }
}
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Runtime.InteropServices

<System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
Public Class Form1
    Inherits System.Windows.Forms.Form

    Private nwl As MyNativeWindowListener
    Private nw As MyNativeWindow

    Friend Sub ApplicationActivated(ByVal ApplicationActivated As Boolean)
        ' The application has been activated or deactivated
        System.Diagnostics.Debug.WriteLine("Application Active = " + ApplicationActivated.ToString())
    End Sub

    Private Sub New()
        MyBase.New()

        Me.Size = New System.Drawing.Size(300, 300)
        Me.Text = "Form1"

        nwl = New MyNativeWindowListener(Me)
        nw = New MyNativeWindow(Me)

    End Sub

    Public Shared Sub Main()
        Application.Run(New Form1())
    End Sub
End Class

' NativeWindow class to listen to operating system messages.
Friend Class MyNativeWindowListener
    Inherits NativeWindow

    ' Constant value was found in the "windows.h" header file.
    Private Const WM_ACTIVATEAPP As Integer = &H1C

    Private parent As Form1

    Public Sub New(ByVal parent As Form1)

        AddHandler parent.HandleCreated, AddressOf Me.OnHandleCreated
        AddHandler parent.HandleDestroyed, AddressOf Me.OnHandleDestroyed
        Me.parent = parent
    End Sub

    ' Listen for the control's window creation and hook into it.    
    Private Sub OnHandleCreated(ByVal sender As Object, ByVal e As EventArgs)
        ' Window is now created, assign handle to NativeWindow.
        AssignHandle(CType(sender, Form).Handle)
    End Sub

    Private Sub OnHandleDestroyed(ByVal sender As Object, ByVal e As EventArgs)
        ' Window was destroyed, release hook.
        ReleaseHandle()
    End Sub

    <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
        Protected Overrides Sub WndProc(ByRef m As Message)
        ' Listen for operating system messages

        Select Case (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(m.WParam.ToInt32() <> 0)

        End Select

        MyBase.WndProc(m)
    End Sub
End Class

' MyNativeWindow class to create a window given a class name.
<System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
Friend Class MyNativeWindow
    Inherits NativeWindow

    ' Constant values were found in the "windows.h" header file.
    Private Const WS_CHILD As Integer = &H40000000, _
                  WS_VISIBLE As Integer = &H10000000, _
                  WM_ACTIVATEAPP As Integer = &H1C

    Private windowHandle As Integer

    Public Sub New(ByVal parent As Form)

        Dim cp As CreateParams = 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 Or WS_VISIBLE

        ' Create the actual window
        Me.CreateHandle(cp)
    End Sub

    ' Listen to when the handle changes to keep the variable in sync
    <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
    Protected Overrides Sub OnHandleChange()
        windowHandle = Me.Handle.ToInt32()
    End Sub

    <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
        Protected Overrides Sub WndProc(ByRef m As Message)
        ' Listen for messages that are sent to the button window. Some messages are sent
        ' to the parent window instead of the button's window.

        Select Case (m.Msg)
            Case WM_ACTIVATEAPP
                ' Do something here in response to messages
        End Select

        MyBase.WndProc(m)
    End Sub

End Class

備註

這個類別會自動管理視窗類別建立和註冊。

當視窗與視窗控制碼相關聯時,視窗不符合垃圾收集的資格。 若要確保適當的垃圾收集,您必須使用 手動終結 DestroyHandle 控制碼,或使用 釋放 ReleaseHandle

注意

處理 ReleaseHandle WM_NCDESTROY訊息時,會呼叫 方法。 這表示在某些情況下,當您不需要手動呼叫 ReleaseHandle 時,最好這麼做。

類別 NativeWindow 提供下列屬性和方法來管理控制碼: HandleCreateHandleAssignHandleDestroyHandle 、 和 ReleaseHandle

建構函式

NativeWindow()

初始化 NativeWindow 類別的執行個體。

屬性

Handle

取得這個視窗的控制代碼。

方法

AssignHandle(IntPtr)

將控制代碼指派到這個視窗。

CreateHandle(CreateParams)

使用指定的建立參數建立視窗和它的控制代碼。

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。

(繼承來源 MarshalByRefObject)
DefWndProc(Message)

叫用與這個視窗相關的預設視窗程序。

DestroyHandle()

終結視窗和它的控制代碼。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Finalize()

釋放與這個視窗關聯的資源。

FromHandle(IntPtr)

擷取與指定控制代碼關聯的視窗。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetLifetimeService()
已淘汰.

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。

(繼承來源 MarshalByRefObject)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
InitializeLifetimeService()
已淘汰.

取得存留期服務物件,以控制這個執行個體的存留期原則。

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。

(繼承來源 MarshalByRefObject)
OnHandleChange()

指定告知方法,當視窗的控制代碼變更時便會呼叫該方法。

OnThreadException(Exception)

在衍生類別中覆寫時,管理無法處理的執行緒例外狀況。

ReleaseHandle()

釋放與這個視窗相關的控制代碼。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)
WmDpiChangedAfterParent(Message)

提供視窗控制代碼 (Window Handle) 和視窗程序 (Window Procedure) 的低階封裝。

WmDpiChangedBeforeParent(Message)

提供視窗控制代碼 (Window Handle) 和視窗程序 (Window Procedure) 的低階封裝。

WndProc(Message)

叫用與這個視窗相關的預設視窗程序。

適用於

另請參閱