Bagikan melalui


Cara: Mensimulasikan Peristiwa Mouse dan Keyboard dalam Kode

Formulir Windows menyediakan beberapa opsi untuk mensimulasikan input mouse dan keyboard secara terprogram. Topik ini memberikan gambaran umum tentang opsi ini.

Mensimulasikan Input Mouse

Cara terbaik untuk mensimulasikan peristiwa mouse adalah dengan memanggil Onmetode EventName yang meningkatkan peristiwa mouse yang ingin Anda simulasikan. Opsi ini biasanya hanya dimungkinkan dalam kontrol dan formulir kustom, karena metode yang menaikkan peristiwa dilindungi dan tidak dapat diakses di luar kontrol atau formulir. Misalnya, langkah-langkah berikut menggambarkan cara mensimulasikan mengklik tombol kanan mouse dalam kode.

Untuk mengklik tombol kanan mouse secara terprogram

  1. Buat properti MouseEventArgs yang propertinya Button diatur ke MouseButtons.Right nilai .

  2. OnMouseClick Panggil metode dengan ini MouseEventArgs sebagai argumen .

Untuk informasi selengkapnya tentang kontrol kustom, lihat Mengembangkan Kontrol Formulir Windows pada Waktu Desain.

Ada cara lain untuk mensimulasikan input mouse. Misalnya, Anda dapat secara terprogram mengatur properti kontrol yang mewakili status yang biasanya diatur melalui input mouse (seperti Checked properti CheckBox kontrol), atau Anda dapat langsung memanggil delegasi yang dilampirkan ke peristiwa yang ingin Anda simulasikan.

Mensimulasikan Input Keyboard

Meskipun Anda dapat mensimulasikan input keyboard dengan menggunakan strategi yang dibahas di atas untuk input mouse, Formulir Windows juga menyediakan SendKeys kelas untuk mengirim penekanan tombol ke aplikasi aktif.

Perhatian

Jika aplikasi Anda ditujukan untuk penggunaan internasional dengan berbagai keyboard, penggunaan SendKeys.Send dapat menghasilkan hasil yang tidak dapat diprediksi dan harus dihindari.

Catatan

Kelas SendKeys telah diperbarui untuk .NET Framework 3.0 untuk mengaktifkan penggunaannya dalam aplikasi yang berjalan di Windows Vista. Peningkatan keamanan Windows Vista (dikenal sebagai Kontrol Akun Pengguna atau UAC) mencegah implementasi sebelumnya bekerja seperti yang diharapkan.

Kelas SendKeys ini rentan terhadap masalah waktu, yang harus dikerjakan oleh beberapa pengembang. Implementasi yang diperbarui masih rentan terhadap masalah waktu, tetapi sedikit lebih cepat dan mungkin memerlukan perubahan pada solusi. Kelas SendKeys mencoba menggunakan implementasi sebelumnya terlebih dahulu, dan jika itu gagal, menggunakan implementasi baru. Akibatnya, SendKeys kelas mungkin berperilaku berbeda pada sistem operasi yang berbeda. Selain itu, ketika SendKeys kelas menggunakan implementasi baru, SendWait metode tidak akan menunggu pesan diproses ketika dikirim ke proses lain.

Jika aplikasi Anda bergantung pada perilaku yang konsisten terlepas dari sistem operasi, Anda dapat memaksa SendKeys kelas untuk menggunakan implementasi baru dengan menambahkan pengaturan aplikasi berikut ke file app.config Anda.

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

Untuk memaksa SendKeys kelas menggunakan implementasi sebelumnya, gunakan nilai "JournalHook" sebagai gantinya.

Untuk mengirim penekanan tombol ke aplikasi yang sama

  1. Send Panggil metode atau SendWait kelas SendKeys . Penekanan kunci yang ditentukan akan diterima oleh kontrol aktif aplikasi. Contoh kode berikut menggunakan Send untuk mensimulasikan penekanan tombol ENTER saat pengguna mengklik dua kali permukaan formulir. Contoh ini mengasumsikan Form dengan kontrol tunggal Button yang memiliki indeks tab 0.

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

Untuk mengirim penekanan tombol ke aplikasi lain

  1. Aktifkan jendela aplikasi yang akan menerima penekanan tombol, lalu panggil Send metode atau SendWait . Karena tidak ada metode terkelola untuk mengaktifkan aplikasi lain, Anda harus menggunakan metode Windows asli untuk memaksa fokus pada aplikasi lain. Contoh kode berikut menggunakan pemanggilan platform untuk memanggil FindWindow metode dan SetForegroundWindow untuk mengaktifkan jendela aplikasi Kalkulator, lalu memanggil SendWait untuk mengeluarkan serangkaian perhitungan ke aplikasi Kalkulator.

    Catatan

    Parameter FindWindow panggilan yang benar yang menemukan aplikasi Kalkulator bervariasi berdasarkan versi Windows Anda. Kode berikut menemukan aplikasi Kalkulator pada Windows 7. Di Windows Vista, ubah parameter pertama menjadi "SciCalc". Anda dapat menggunakan alat Spy++, yang disertakan dengan Visual Studio, untuk menentukan parameter yang benar.

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

Contoh

Contoh kode berikut adalah aplikasi lengkap untuk contoh kode sebelumnya.

#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());
}
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}");
        }
    }
}
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

Mengompilasi Kode

Contoh ini membutuhkan:

  • Referensi ke rakitan System, System.Drawing dan System.Windows.Forms.

Baca juga