C# sendkeys to other application to particular textfield

前端 未结 1 1578
陌清茗
陌清茗 2021-01-24 05:16

I need to sendkeys to other application to particular textfield in other application using C#.

Is that possible? If yes, can anyone give me sample code?

相关标签:
1条回答
  • 2021-01-24 05:54

    SendKeys only sends the keystroke combinations to the active window.

    So if your C# application calls the SendKeys function at precisely the right time, when the user has that other application's textbox focused, everything will work just fine.

    The problem, of course, is that the real world is rarely this perfect. You don't know exactly when the user will have the other application focused, and certainly won't know if they've clicked in the textbox control. You also won't have any way for the user to tell your C# application when to send the text (such as clicking a button) because in order to click the button, your application must have the foreground focus, and therefore not the application that you want to receive the keyboard input.

    And that's just a brief overview of some of the potential problems you'll encounter when trying to do UI automation this way. This is extremely fragile, and can easily lead to some unexpected, infuriating behavior for the user. I strongly recommend against it. A much better option is communicating directly with the other application, such as by sending it messages, rather than trying to invasively control its UI.

    If you absolutely must do this, despite all recommendations to the contrary, the best way is to get the handle to the window you want to send the text to, and then send a WM_SETTEXT message. That will, of course, require that you P/Invoke a few functions from the Win32 API. See the answers to this question for some sample code.

    0 讨论(0)
提交回复
热议问题