简体   繁体   English

使用C#在Windows XP上发送奇怪的行为

[英]SendKeys strange behaviour on Windows XP in C#

I am using SendKeys in one of my program (C#) which copies selected text when a user presses F8 on keyboard. 我在我的一个程序(C#)中使用SendKeys,当用户按下键盘上的F8时,它会复制所选文本。

It is working fine on Windows 7 but on Windows XP it has the following problem. 它在Windows 7上运行良好,但在Windows XP上它有以下问题。

  1. Suppose on notepad, following sentence is written "This is test" 假设在记事本上,下面的句子写成“这是测试”

  2. If user selects "is" and presses F8 then the text is not copied. 如果用户选择“是”并按F8,则不复制文本。

  3. After that if user selects "This" then the text copied is "is" 之后,如果用户选择“This”,则复制的文本为“is”

  4. After that if user selects "test" then the text copied is "This" 之后,如果用户选择“test”,则复制的文本为“This”

As you can see pressing F8 copies previously selected text and not the current one. 如您所见,按F8可复制以前选择的文本,而不是当前文本。 It is only happening on Windows XP. 它只发生在Windows XP上。

Here is the code 这是代码

System.IntPtr test = GetForegroundWindow();
System.Windows.Forms.SendKeys.Send("^(c)");
string copiedText = Clipboard.GetText();

Since I am using global key binding for F8 hence the first line of code tells me the currently active window. 由于我使用F8的全局键绑定,因此第一行代码告诉我当前活动的窗口。 After that Ctrl+C is sent and then text is copied from clipboard. 之后,发送Ctrl + C,然后从剪贴板复制文本。

I'd suggest switching to using the SendWait method: 我建议切换到使用SendWait方法:

Use SendWait to send keystrokes or combinations of keystrokes to the active application and wait for the keystroke messages to be processed. 使用SendWait将键击或键击组合发送到活动应用程序,并等待处理击键消息。

(Emphasis added) (重点补充)

At the moment, you have a race condition, with no guarantee that the other application has processed the CTRL-C before you attempt to read the clipboard contents. 目前,您有竞争条件,在尝试读取剪贴板内容之前,无法保证其他应用程序已处理CTRL-C。 It's not surprising that sometimes you get the older contents. 有时你得到较旧的内容并不奇怪。

(Insert usual caveats about SendKeys being a horrific way to automate other applications, consider using the automation API instead, and avoid trampling all over the clipboard unless necessary) (插入关于SendKeys常见警告是一种自动化其他应用程序的可怕方式,请考虑使用自动化API ,并避免在整个剪贴板中踩踏,除非必要)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM