Simple Application for sending Keystroke in VB.NET

前端 未结 2 703
-上瘾入骨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:30

    Button has focus. Button click event sends an enter keystroke. Sending an enter causes the button click event to fire. Infinite loop.

    You could disable the button before and re-enable the button after the sendkeys routine is done to stop the infinite loop.

    What you probably would want to do is switch the focus back to the application you want to send your keystrokes to.

    0 讨论(0)
  • 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("=");
    }
    
    0 讨论(0)
提交回复
热议问题