C# 将密钥发送到其他应用程序到特定文本字段

发布于 2024-11-08 01:51:34 字数 74 浏览 2 评论 0原文

我需要使用 C# 将密钥发送到其他应用程序到其他应用程序中的特定文本字段。

这可能吗?如果是,有人可以给我示例代码吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

生死何惧 2024-11-15 01:51:34

SendKeys仅将击键组合发送到活动窗口

因此,如果您的 C# 应用程序在正确的时间调用 SendKeys 函数,那么当用户将其他应用程序的文本框聚焦时,一切都会正常工作。

当然,问题在于现实世界很少如此完美。您不知道用户何时会聚焦其他应用程序,当然也不知道他们是否单击了文本框控件。您也无法让用户告诉您的 C# 应用程序何时发送文本(例如单击按钮),因为为了单击该按钮,您的 > 应用程序必须具有前台焦点,因此不是您想要接收键盘输入的应用程序。

这只是您在尝试以这种方式实现 UI 自动化时可能遇到的一些潜在问题的简要概述。这是非常脆弱的,很容易导致用户出现一些意想不到的、令人恼火的行为。我强烈建议反对。更好的选择是直接与其他应用程序通信,例如通过向其发送消息,而不是尝试侵入性地控制其 UI。

如果您绝对必须这样做,尽管所有建议都是相反的,但最好的方法是获取要将文本发送到的窗口的句柄,然后发送 WM_SETTEXT 消息。当然,这需要您从 Win32 API 中 P/Invoke 一些函数。请参阅此问题的答案一些示例代码。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文