Exportar (0) Imprimir
Expandir todo

NativeWindow (Clase)

Proporciona una encapsulación de bajo nivel de un identificador de ventana y un procedimiento de ventana.

Espacio de nombres: System.Windows.Forms
Ensamblado: System.Windows.Forms (en system.windows.forms.dll)

public class NativeWindow : MarshalByRefObject, IWin32Window
public class NativeWindow extends MarshalByRefObject implements IWin32Window
public class NativeWindow extends MarshalByRefObject implements IWin32Window
No aplicable.

Esta clase administra automáticamente la creación y el registro de las clases de ventana.

Una ventana no es susceptible de ser detectada durante la recolección de elementos no utilizados cuando está asociada a un identificador de ventana. Para garantizar que la recolección de elementos no utilizados se realiza correctamente, los identificadores deben destruirse manualmente mediante el método DestroyHandle o deben liberarse mediante el método ReleaseHandle.

NotaNota:

Se llama al método ReleaseHandle cuando se procesa el mensaje WM_NCDESTROY. Esto significa que hay casos en los que no es necesario llamar manualmente a ReleaseHandle, pero es recomendable hacerlo.

La clase NativeWindow proporciona las propiedades y los métodos siguientes para administrar los identificadores: Handle, CreateHandle, AssignHandle, DestroyHandle y ReleaseHandle.

En el siguiente ejemplo de código se muestra cómo se interceptan los mensajes de ventana del sistema operativo en un procedimiento de ventana y cómo se crea una ventana con un nombre de clase de ventana de un sistema operativo específico. En el ejemplo se crean dos clases que se heredan de NativeWindow y que realizan esta operación.

La clase MyNativeWindowListener se enlaza al procedimiento de ventana del formulario que se pasó al constructor y reemplaza el método WndProc para interceptar el mensaje de ventana WM_ACTIVATEAPP. La clase muestra el uso de los métodos AssignHandle y ReleaseHandle para identificar el identificador de ventana que utilizará NativeWindow. El identificador se asigna en función de los eventos Control.HandleCreated y Control.HandleDestroyed. Cuando se recibe el mensaje de ventana WM_ACTIVATEAPP, la clase llama al método form1ApplicationActivated.

La clase MyNativeWindow crea una nueva ventana con la propiedad ClassName establecida en BUTTON. La clase muestra la forma de utilizar el método CreateHandle y la forma de reemplazar el método WndProc para interceptar los mensajes de ventana recibidos.

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


package NativeWindowApplication;

import System.*;
import System.Drawing.*;
import System.Windows.Forms.*;
import System.Runtime.InteropServices.*;
import System.Security.Permissions.*;

// Summary description for Form1.

public class Form1 extends System.Windows.Forms.Form
{
    private MyNativeWindowListener nwl;
    private MyNativeWindow nw;

    void ApplicationActived(boolean applicationActivated)
    {
        // The application has been activated or deactivated
        System.Diagnostics.Debug.WriteLine("Application Active = " 
            + Convert.ToString(applicationActivated));
    } //ApplicationActived

    public Form1()
    {
        this.set_Size(new System.Drawing.Size(300, 300));
        this.set_Text("Form1");

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

    // The main entry point for the application.
    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        Application.Run(new Form1());
    } //main
} //Form1

// NativeWindow class to listen to operating system messages.
/** @attribute SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)
 */
public class MyNativeWindowListener extends NativeWindow
{
    // Constant value was found in the "windows.h" header file.
    private int WM_ACTIVATEAPP = 0x1C;
    private Form1 parent;

    public MyNativeWindowListener(Form1 parent)
    {
        parent.add_HandleCreated(new EventHandler(this.OnHandleCreated));
        parent.add_HandleDestroyed(new EventHandler(this.OnHandleDestroyed));
        this.parent = parent;
    } //MyNativeWindowListener

    // 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(((Form1)sender).get_Handle());
    } //OnHandleCreated

    void OnHandleDestroyed(Object sender, EventArgs e)
    {
        // Window was destroyed, release hook.
        ReleaseHandle();
    } //OnHandleDestroyed

    protected void WndProc(Message m)
    {
        // Listen for operating system messages
        if (m.get_Msg() == WM_ACTIVATEAPP) {
            // Notify the form that this message was received.
            // Application is activated or deactivated, 
            // based upon the WParam parameter.
            parent.ApplicationActived(m.get_WParam().ToInt32() != 0);
        }
        super.WndProc(m);
    } //WndProc
} //MyNativeWindowListener

// MyNativeWindow class to create a window given a class name.
/** @attribute SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)
 */
public class MyNativeWindow extends NativeWindow
{
    // Constant values were found in the "windows.h" header file.
    private int WS_CHILD = 0x40000000;
    private int WS_VISIBLE = 0x10000000;
    private int WM_ACTIVATEAPP = 0x1C;
    private int windowHandle;

    public MyNativeWindow(Form parent)
    {
        CreateParams cp = new CreateParams();

        // Fill in the CreateParams details.
        cp.set_Caption("Click here");
        cp.set_ClassName("Button");

        // Set the position on the form
        cp.set_X(100);
        cp.set_Y(100);
        cp.set_Height(100);
        cp.set_Width(100);

        // Specify the form as the parent.
        cp.set_Parent(parent.get_Handle());

        // Create as a child of the specified parent
        cp.set_Style(WS_CHILD | WS_VISIBLE);

        // Create the actual window
        this.CreateHandle(cp);
    } //MyNativeWindow

    // Listen to when the handle changes to keep the variable in sync
    protected void OnHandleChange()
    {
        windowHandle = this.get_Handle().ToInt32();
    } //OnHandleChange

    protected void WndProc(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.
        if (m.get_Msg() == WM_ACTIVATEAPP) {
            // Do something here in response to messages
        }
        super.WndProc(m);
    } //WndProc
} //MyNativeWindow

  • SecurityPermission  para que las clases herederas llamen al código no administrado. Enumeración asociada: SecurityPermissionFlag.UnmanagedCode.
  • SecurityPermission  para que el llamador inmediato llame al código no administrado. Enumeración asociada: SecurityPermissionFlag.UnmanagedCode.

System.Object
   System.MarshalByRefObject
    System.Windows.Forms.NativeWindow

Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Windows 98, Windows 2000 Service Pack 4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter

Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.

.NET Framework

Compatible con: 3.0, 2.0, 1.1, 1.0
Mostrar:
© 2014 Microsoft