Share via


Cómo: Simular eventos del mouse y del teclado en el código

Los formularios Windows Forms proporcionan varias opciones para simular mediante programación las entradas del mouse y del teclado. En este tema se proporciona información general sobre estas opciones.

Simular la entrada del mouse

La mejor manera de simular los eventos del mouse es llamar al método OnEventName que provoque el evento del mouse que desee simular. Esta opción normalmente sólo es posible en los controles y formularios personalizados, porque los métodos que provocan eventos están protegidos y no se puede obtener acceso a ellos fuera del control o del formulario. Por ejemplo, en los pasos siguientes se muestra cómo simular el hacer clic con el botón secundario del mouse en el código.

Para hacer clic con el botón secundario del mouse mediante programación

  1. Cree un MouseEventArgs cuya propiedad Button se establezca en el valor MouseButtons.Right.

  2. Llame al método OnMouseClick con este MouseEventArgs como argumento.

Para obtener más información sobre controles personalizados, vea Desarrollar controles de formularios Windows Forms en tiempo de diseño.

Hay otras maneras de simular las entradas del mouse. Por ejemplo, se puede establecer mediante programación una propiedad de control que representa un estado que se establece normalmente mediante las entradas del mouse (como la propiedad Checked del control CheckBox), o se puede llamar directamente al delegado asociado al evento que desea simular.

Simular la entrada del teclado

Aunque puede simular la entrada del teclado mediante las estrategias descritas anteriormente para la entrada del mouse, los formularios Windows Forms también proporcionan la clase SendKeys para enviar a la ventana activa la información de haber presionado las teclas.

Nota de precauciónPrecaución

Si está previsto el uso internacional de la aplicación con distintos teclados, el uso de SendKeys.Send podría causar resultados imprevistos y por tanto debe evitarse.

Nota

La clase SendKeys se ha actualizado para que .NET Framework 3.0 pueda habilitar su uso en aquellas aplicaciones que se ejecuten en Windows Vista. La seguridad mejorada de Windows Vista (conocida como Control de cuentas de usuario o UAC) impide que la implementación anterior funcione según lo previsto.

La clase SendKeys es sensible a los problemas de sincronización, para los que algunos programadores han tenido que encontrar una solución alternativa. La implementación actualizada todavía es sensible a los problemas de sincronización, pero es ligeramente más rápida y puede requerir cambios en las soluciones ideadas. La clase SendKeys intenta utilizar primero la implementación anterior y, si da error, usa la nueva implementación. Como resultado, la clase SendKeys puede comportarse de distinta manera en sistemas operativos diferentes. Además, cuando la clase SendKeys usa la nueva implementación, el método SendWait no espera a que se procesen los mensajes cuando se envían a otro proceso.

Si la aplicación necesita un comportamiento coherente independiente del sistema operativo, puede obligar a que la clase SendKeys utilice la nueva implementación, agregando la configuración de aplicación siguiente al archivo app.config.

<appSettings>

<add key="SendKeys" value="SendInput"/>

</appSettings>

Para forzar que la clase SendKeys use la implementación anterior, utilice en su lugar el valor "JournalHook".

Para enviar una pulsación de tecla a la misma aplicación

  • Llame al método Send oSendWait de la clase SendKeys. El control activo de la aplicación recibirá las pulsaciones de tecla especificadas. En el ejemplo de código siguiente se utiliza el método Send para simular la pulsación de la tecla INTRO cuando el usuario hace doble clic en el formulario. En este ejemplo se supone que un Form con un único control Button tiene un índice de tabulación de 0.

    ' Send a key to the button when the user double-clicks anywhere 
    ' on the form.
    Private Sub Form1_DoubleClick(ByVal sender As Object, _
        ByVal e As EventArgs) Handles Me.DoubleClick
    
        ' Send the enter key to the button, which raises the click 
        ' event for the button. This works because the tab stop of 
        ' the button is 0.
        SendKeys.Send("{ENTER}")
    End Sub
    
    // Send a key to the button when the user double-clicks anywhere 
    // on the form.
    private void Form1_DoubleClick(object sender, EventArgs e)
    {
        // Send the enter key to the button, which raises the click 
        // event for the button. This works because the tab stop of 
        // the button is 0.
        SendKeys.Send("{ENTER}");
    }
    
        // Send a key to the button when the user double-clicks anywhere
        // on the form.
    private:
        void Form1_DoubleClick(Object^ sender, EventArgs^ e)
        {
            // Send the enter key to the button, which triggers the click
            // event for the button. This works because the tab stop of
            // the button is 0.
            SendKeys::Send("{ENTER}");
        }
    

Para enviar una pulsación de tecla a otra aplicación

  • Active la ventana de la aplicación que recibirá las pulsaciones de tecla y, a continuación, llame al método Send o SendWait. Debido a que no existe un método administrado para activar otra aplicación, se pueden utilizar métodos nativos de Windows para forzar el desplazamiento del foco a otras aplicaciones. En el ejemplo de código siguiente se utiliza la invocación de plataforma para llamar a los métodos FindWindow y SetForegroundWindow activar la ventana de la aplicación Calculadora y, a continuación, se llama al método SendWait para enviar una serie de cálculos a la aplicación Calculadora.

    Nota

    Los parámetros correctos de la llamada a FindWindow que busca la aplicación Calculadora varían en función de la versión de Windows. El código siguiente encuentra la aplicación Calculadora en Windows 7. En Windows Vista, cambie el primer parámetro por "SciCalc". Puede usar la herramienta Spy++, incluida con Visual Studio, para determinar los parámetros correctos.

    ' Get a handle to an application window.
    Declare Auto Function FindWindow Lib "USER32.DLL" ( _
        ByVal lpClassName As String, _
        ByVal lpWindowName As String) As IntPtr
    
    ' Activate an application window.
    Declare Auto Function SetForegroundWindow Lib "USER32.DLL" _
        (ByVal hWnd As IntPtr) As Boolean
    
    ' Send a series of key presses to the Calculator application.
    Private Sub button1_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles button1.Click
    
        ' Get a handle to the Calculator application. The window class
        ' and window name were obtained using the Spy++ tool.
        Dim calculatorHandle As IntPtr = FindWindow("CalcFrame", "Calculator")
    
        ' Verify that Calculator is a running process.
        If calculatorHandle = IntPtr.Zero Then
            MsgBox("Calculator is not running.")
            Return
        End If
    
        ' Make Calculator the foreground application and send it 
        ' a set of calculations.
        SetForegroundWindow(calculatorHandle)
        SendKeys.SendWait("111")
        SendKeys.SendWait("*")
        SendKeys.SendWait("11")
        SendKeys.SendWait("=")
    End Sub
    
    // Get a handle to an application window.
    [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
    public static extern IntPtr FindWindow(string lpClassName,
        string lpWindowName);
    
    // Activate an application window.
    [DllImport("USER32.DLL")]
    public static extern bool SetForegroundWindow(IntPtr hWnd);
    
    // Send a series of key presses to the Calculator application.
    private void button1_Click(object sender, EventArgs e)
    {
        // Get a handle to the Calculator application. The window class
        // and window name were obtained using the Spy++ tool.
        IntPtr calculatorHandle = FindWindow("CalcFrame","Calculator");
    
        // Verify that Calculator is a running process.
        if (calculatorHandle == IntPtr.Zero)
        {
            MessageBox.Show("Calculator is not running.");
            return;
        }
    
        // Make Calculator the foreground application and send it 
        // a set of calculations.
        SetForegroundWindow(calculatorHandle);
        SendKeys.SendWait("111");
        SendKeys.SendWait("*");
        SendKeys.SendWait("11");
        SendKeys.SendWait("=");
    }
    
            // Get a handle to an application window.
        public:
            [DllImport("USER32.DLL", CharSet = CharSet::Unicode)]
            static IntPtr FindWindow(String^ lpClassName, String^ lpWindowName);
        public:
            // Activate an application window.
            [DllImport("USER32.DLL")]
            static bool SetForegroundWindow(IntPtr hWnd);
    
            // Send a series of key presses to the Calculator application.
        private:
            void button1_Click(Object^ sender, EventArgs^ e)
            {
                // Get a handle to the Calculator application. The window class
                // and window name were obtained using the Spy++ tool.
                IntPtr calculatorHandle = FindWindow("CalcFrame", "Calculator");
    
                // Verify that Calculator is a running process.
                if (calculatorHandle == IntPtr::Zero)
                {
                    MessageBox::Show("Calculator is not running.");
                    return;
                }
    
                // Make Calculator the foreground application and send it
                // a set of calculations.
                SetForegroundWindow(calculatorHandle);
                SendKeys::SendWait("111");
                SendKeys::SendWait("*");
                SendKeys::SendWait("11");
                SendKeys::SendWait("=");
            }
    

Ejemplo

En el siguiente código de ejemplo se muestra la aplicación completa de los ejemplos de código anteriores.

Imports System
Imports System.Runtime.InteropServices
Imports System.Drawing
Imports System.Windows.Forms

Namespace SimulateKeyPress

    Class Form1
        Inherits Form
        Private WithEvents button1 As New Button()

        <STAThread()> _
        Public Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub

        Public Sub New()
            button1.Location = New Point(10, 10)
            button1.TabIndex = 0
            button1.Text = "Click to automate Calculator"
            button1.AutoSize = True
            Me.Controls.Add(button1)
        End Sub

        ' Get a handle to an application window.
        Declare Auto Function FindWindow Lib "USER32.DLL" ( _
            ByVal lpClassName As String, _
            ByVal lpWindowName As String) As IntPtr

        ' Activate an application window.
        Declare Auto Function SetForegroundWindow Lib "USER32.DLL" _
            (ByVal hWnd As IntPtr) As Boolean

        ' Send a series of key presses to the Calculator application.
        Private Sub button1_Click(ByVal sender As Object, _
            ByVal e As EventArgs) Handles button1.Click

            ' Get a handle to the Calculator application. The window class
            ' and window name were obtained using the Spy++ tool.
            Dim calculatorHandle As IntPtr = FindWindow("CalcFrame", "Calculator")

            ' Verify that Calculator is a running process.
            If calculatorHandle = IntPtr.Zero Then
                MsgBox("Calculator is not running.")
                Return
            End If

            ' Make Calculator the foreground application and send it 
            ' a set of calculations.
            SetForegroundWindow(calculatorHandle)
            SendKeys.SendWait("111")
            SendKeys.SendWait("*")
            SendKeys.SendWait("11")
            SendKeys.SendWait("=")
        End Sub

        ' Send a key to the button when the user double-clicks anywhere 
        ' on the form.
        Private Sub Form1_DoubleClick(ByVal sender As Object, _
            ByVal e As EventArgs) Handles Me.DoubleClick

            ' Send the enter key to the button, which raises the click 
            ' event for the button. This works because the tab stop of 
            ' the button is 0.
            SendKeys.Send("{ENTER}")
        End Sub

    End Class
End Namespace
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Windows.Forms;

namespace SimulateKeyPress
{
    class Form1 : Form
    {
        private Button button1 = new Button();

        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

        public Form1()
        {
            button1.Location = new Point(10, 10);
            button1.TabIndex = 0;
            button1.Text = "Click to automate Calculator";
            button1.AutoSize = true;
            button1.Click += new EventHandler(button1_Click);

            this.DoubleClick += new EventHandler(Form1_DoubleClick);
            this.Controls.Add(button1);
        }

        // Get a handle to an application window.
        [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindow(string lpClassName,
            string lpWindowName);

        // Activate an application window.
        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        // Send a series of key presses to the Calculator application.
        private void button1_Click(object sender, EventArgs e)
        {
            // Get a handle to the Calculator application. The window class
            // and window name were obtained using the Spy++ tool.
            IntPtr calculatorHandle = FindWindow("CalcFrame","Calculator");

            // Verify that Calculator is a running process.
            if (calculatorHandle == IntPtr.Zero)
            {
                MessageBox.Show("Calculator is not running.");
                return;
            }

            // Make Calculator the foreground application and send it 
            // a set of calculations.
            SetForegroundWindow(calculatorHandle);
            SendKeys.SendWait("111");
            SendKeys.SendWait("*");
            SendKeys.SendWait("11");
            SendKeys.SendWait("=");
        }

        // Send a key to the button when the user double-clicks anywhere 
        // on the form.
        private void Form1_DoubleClick(object sender, EventArgs e)
        {
            // Send the enter key to the button, which raises the click 
            // event for the button. This works because the tab stop of 
            // the button is 0.
            SendKeys.Send("{ENTER}");
        }
    }
}
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
#using <System.dll>

using namespace System;
using namespace System::Runtime::InteropServices;
using namespace System::Drawing;
using namespace System::Windows::Forms;

namespace SimulateKeyPress
{

    public ref class Form1 : public Form
    {
    public:
        Form1()
        {
            Button^ button1 = gcnew Button();
            button1->Location = Point(10, 10);
            button1->TabIndex = 0;
            button1->Text = "Click to automate Calculator";
            button1->AutoSize = true;
            button1->Click += gcnew EventHandler(this, &Form1::button1_Click);

            this->DoubleClick += gcnew EventHandler(this, 
                &Form1::Form1_DoubleClick);
            this->Controls->Add(button1);
        }

        // Get a handle to an application window.
    public:
        [DllImport("USER32.DLL", CharSet = CharSet::Unicode)]
        static IntPtr FindWindow(String^ lpClassName, String^ lpWindowName);
    public:
        // Activate an application window.
        [DllImport("USER32.DLL")]
        static bool SetForegroundWindow(IntPtr hWnd);

        // Send a series of key presses to the Calculator application.
    private:
        void button1_Click(Object^ sender, EventArgs^ e)
        {
            // Get a handle to the Calculator application. The window class
            // and window name were obtained using the Spy++ tool.
            IntPtr calculatorHandle = FindWindow("CalcFrame", "Calculator");

            // Verify that Calculator is a running process.
            if (calculatorHandle == IntPtr::Zero)
            {
                MessageBox::Show("Calculator is not running.");
                return;
            }

            // Make Calculator the foreground application and send it
            // a set of calculations.
            SetForegroundWindow(calculatorHandle);
            SendKeys::SendWait("111");
            SendKeys::SendWait("*");
            SendKeys::SendWait("11");
            SendKeys::SendWait("=");
        }

        // Send a key to the button when the user double-clicks anywhere
        // on the form.
    private:
        void Form1_DoubleClick(Object^ sender, EventArgs^ e)
        {
            // Send the enter key to the button, which triggers the click
            // event for the button. This works because the tab stop of
            // the button is 0.
            SendKeys::Send("{ENTER}");
        }
    };
}

[STAThread]
int main()
{
    Application::EnableVisualStyles();
    Application::Run(gcnew SimulateKeyPress::Form1());
}

Compilar el código

Para este ejemplo se necesita:

  • Referencias a los ensamblados System, System.Drawing y System.Windows.Forms.

Para obtener información sobre la compilación de este ejemplo desde la línea de comandos de Visual Basic o Visual C#, vea Generar desde la línea de comandos (Visual Basic) o Compilar la línea de comandos con csc.exe. También puede compilar este ejemplo en Visual Studio pegando el código en un proyecto nuevo. Para obtener más información, vea Cómo: Compilar y ejecutar un ejemplo de código completo de formularios Windows Forms utilizando Visual Studio y Cómo: Compilar y ejecutar un ejemplo de código completo de formularios Windows Forms utilizando Visual Studio y Cómo: Compilar y ejecutar un ejemplo de código completo de formularios Windows Forms utilizando Visual Studio y Cómo: Compilar y ejecutar un ejemplo de código completo de Windows Forms en Visual Studio y Cómo: Compilar y ejecutar un ejemplo de código completo de Windows Forms en Visual Studio.

Vea también

Otros recursos

Datos proporcionados por el usuario en formularios Windows Forms