I am using SendKeys in one of my program (C#) which copies selected text when a user presses F8 on keyboard.
It is working fine on Windows 7 but on Windows XP it has the following problem.
-
Suppose on notepad, following sentence is written “This is test”
-
If user selects “is” and presses F8 then the text is not copied.
-
After that if user selects “This” then the text copied is “is”
-
After that if user selects “test” then the text copied is “This”
As you can see pressing F8 copies previously selected text and not the current one. It is only happening on 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. After that Ctrl+C is sent and then text is copied from clipboard.
I’d suggest switching to using the
SendWaitmethod:(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. It’s not surprising that sometimes you get the older contents.
(Insert usual caveats about
SendKeysbeing a horrific way to automate other applications, consider using the automation API instead, and avoid trampling all over the clipboard unless necessary)