Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original
Este tópico ainda não foi avaliado como - Avalie este tópico

Classe NativeWindow

Fornece um encapsulamento de nível baixo de um identificador de janela e um procedimento de janela.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (em System.Windows.Forms.dll)
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public class NativeWindow : MarshalByRefObject, 
	IWin32Window

Essa classe gerencia automaticamente a criação de classes de janela e o inscrição.

Uma janela não está qualificada para lixo coleção quando ele está associado a um identificador de janela. Para garantir a coleta de lixo adequado, alças devem tanto ser destruídas manualmente usando DestroyHandle ou liberada, usando ReleaseHandle.

Observação Observação:

O ReleaseHandle método é chamado quando a mensagem WM_NCDESTROY é processada. Isso significa que há casos em que, quando você não precisará manualmente telefonar ReleaseHandle, mas é uma mercadoria prática de fazer isso.

The NativeWindow classe oferece os seguintes propriedades e métodos para gerenciar alças: Handle, CreateHandle, , AssignHandle, DestroyHandle, e ReleaseHandle.

O exemplo de código a seguir demonstra interceptando mensagens de janela do sistema operacional em um procedimento de janela e criando uma janela com um nome de classe de janela específica do sistema operacional. O exemplo cria duas classes que herdam de NativeWindow que fazer isso.

The MyNativeWindowListener classe conecta para o procedimento de janela de formulário passado no construtor e substitui o WndProc método para interceptar o WM_ACTIVATEAPP mensagem da janela. A classe demonstra o uso do AssignHandle e ReleaseHandle métodos para identificar o identificador da janela do NativeWindow será usado. O identificador é atribuir como baseada o Control.HandleCreated e Control.HandleDestroyed eventos. When the WM_ACTIVATEAPP window message is received, the class calls the form1ApplicationActivated method.

The MyNativeWindow classe cria uma nova janela com o ClassName conjunto para BUTTON. A classe demonstra o uso de CreateHandle método e substituindo o WndProc método para interceptar janela mensagens recebidas.

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")]
    publicclass Form1 : System.Windows.Forms.Form
    {
        private MyNativeWindowListener nwl;
        private MyNativeWindow nw;

        internalvoid 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]
        staticvoid Main()
        {
            Application.Run(new Form1());
        }
    }

    // NativeWindow class to listen to operating system messages.
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    internalclass MyNativeWindowListener : NativeWindow
    {

        // Constant value was found in the "windows.h" header file.
        privateconstint 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.internalvoid OnHandleCreated(object sender, EventArgs e)
        {
            // Window is now created, assign handle to NativeWindow.
            AssignHandle(((Form1)sender).Handle);
        }
        internalvoid OnHandleDestroyed(object sender, EventArgs e)
        {
            // Window was destroyed, release hook.
            ReleaseHandle();
        }
        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
        protectedoverridevoid WndProc(ref Message m)
        {
            // Listen for operating system messagesswitch (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")]
    internalclass MyNativeWindow : NativeWindow
    {

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

        privateint 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 windowthis.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")]
        protectedoverridevoid OnHandleChange()
        {
            windowHandle = (int)this.Handle;
        }

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


System.Object
  System.MarshalByRefObject
    System.Windows.Forms.NativeWindow
Quaisquer membros static (Shared no Visual Basic) públicos deste tipo são thread-safe. Não há garantia de que qualquer membro de instância seja thread-safe.

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

o.NET Framework e.NET Compact Framework não oferecem suporte a todas as versões de cada plataforma. Para obter uma lista de versões suportadas, consulte Requisitos de sistema do .NET framework.

.NET Framework

Compatível com: 3.5, 3.0, 2.0, 1.1, 1.0
Isso foi útil para você?
(1500 caracteres restantes)
Conteúdo da Comunidade Adicionar