Simple Application for sending Keystroke in VB.NET

前端 未结 2 707
-上瘾入骨i
-上瘾入骨i 2020-12-12 06:55

I have an issue regarding Sendkeys Class, as i want to use this class in order to send some keystroke to the active application. As a first step i want to test the {Enter} k

2条回答
  •  悲哀的现实
    2020-12-12 07:32

    In order to sendkey to another application, you need to first activate that application on the button click and then send keys

    MSDN Link

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

提交回复
热议问题