NativeWindow クラス

定義

ウィンドウ ハンドルとウィンドウ プロシージャの下位のカプセル化を提供します。Provides a low-level encapsulation of a window handle and a window procedure.

public ref class NativeWindow : MarshalByRefObject, System::Windows::Forms::IWin32Window
public ref class NativeWindow : MarshalByRefObject
public class NativeWindow : MarshalByRefObject, System.Windows.Forms.IWin32Window
public class NativeWindow : MarshalByRefObject
type NativeWindow = class
    inherit MarshalByRefObject
    interface IWin32Window
type NativeWindow = class
    inherit MarshalByRefObject
Public Class NativeWindow
Inherits MarshalByRefObject
Implements IWin32Window
Public Class NativeWindow
Inherits MarshalByRefObject
継承
NativeWindow
実装

次のコード例は、ウィンドウプロシージャでのオペレーティングシステムのメッセージの受信と、特定のオペレーティングシステムウィンドウのクラス名を持つウィンドウの作成を示しています。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. この例では、これを実現する NativeWindow から継承する2つのクラスを作成します。The example creates two classes that inherit from NativeWindow that accomplish this.

MyNativeWindowListener クラスは、コンストラクターに渡されるフォームのウィンドウプロシージャにフックし、WndProc メソッドをオーバーライドして WM_ACTIVATEAPP ウィンドウメッセージをインターセプトします。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. クラスは、AssignHandleReleaseHandle メソッドを使用して NativeWindow が使用するウィンドウハンドルを識別する方法を示します。The class demonstrates the usage of the AssignHandle and ReleaseHandle methods to identify the window handle the NativeWindow will use. ハンドルは、Control.HandleCreated イベントと Control.HandleDestroyed イベントに基づいて割り当てられます。The handle is assign based upon the Control.HandleCreated and Control.HandleDestroyed events. WM_ACTIVATEAPP ウィンドウメッセージを受信すると、クラスは form1.ApplicationActivated メソッドを呼び出します。When the WM_ACTIVATEAPP window message is received, the class calls the form1.ApplicationActivated method.

MyNativeWindow クラスは、ClassNameBUTTONに設定された新しいウィンドウを作成します。The MyNativeWindow class creates a new window with the ClassName set to BUTTON. クラスは、CreateHandle メソッドを使用し、WndProc メソッドをオーバーライドして、受信されたウィンドウメッセージをインターセプトする方法を示します。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
{
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.
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    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.
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    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();
        }
        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
        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.
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    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
        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
        protected override void OnHandleChange()
        {
            windowHandle = (int)this.Handle;
        }

        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
        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

注釈

このクラスは、ウィンドウクラスの作成と登録を自動的に管理します。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. 適切なガベージコレクションを確実に行うには、DestroyHandle を使用して手動で破棄するか、ReleaseHandleを使用して解放する必要があります。To ensure proper garbage collection, handles must either be destroyed manually using DestroyHandle or released using ReleaseHandle.

注意

ReleaseHandle メソッドは、WM_NCDESTROY メッセージが処理されるときに呼び出されます。The ReleaseHandle method is called when the WM_NCDESTROY message is processed. つまり、手動で ReleaseHandleを呼び出す必要がない場合には、この方法を使用することをお勧めします。This means there are cases in which when you do not need to manually call ReleaseHandle, but it is good practice to do so.

NativeWindow クラスには、ハンドルを管理するための次のプロパティとメソッドが用意されています: HandleCreateHandleAssignHandleDestroyHandle、および ReleaseHandleThe NativeWindow class provides the following properties and methods to manage handles: Handle, CreateHandle, AssignHandle, DestroyHandle, and ReleaseHandle.

コンストラクター

NativeWindow()

NativeWindow クラスのインスタンスを初期化します。Initializes an instance of the NativeWindow class.

プロパティ

Handle

ウィンドウのハンドルを取得します。Gets the handle for this window.

メソッド

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.

(継承元 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.

(継承元 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.

(継承元 Object)
GetLifetimeService()

対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(継承元 MarshalByRefObject)
GetType()

現在のインスタンスの Type を取得します。Gets the Type of the current instance.

(継承元 Object)
InitializeLifetimeService()

このインスタンスの有効期間ポリシーを制御する有効期間サービス オブジェクトを取得します。Obtains a lifetime service object to control the lifetime policy for this instance.

(継承元 MarshalByRefObject)
MemberwiseClone()

現在の Object の簡易コピーを作成します。Creates a shallow copy of the current Object.

(継承元 Object)
MemberwiseClone(Boolean)

現在の MarshalByRefObject オブジェクトの簡易コピーを作成します。Creates a shallow copy of the current MarshalByRefObject object.

(継承元 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()

現在のオブジェクトを表す string を返します。Returns a string that represents the current object.

(継承元 Object)
WndProc(Message)

ウィンドウに関連付けられている既定のウィンドウ プロシージャを呼び出します。Invokes the default window procedure associated with this window.

適用対象

こちらもご覧ください