0

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.

  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.

  3. After that if user selects "This" then the text copied is "is"

  4. 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.

Ali
  • 1,801
  • 6
  • 43
  • 58

1 Answers1

2

I'd suggest switching to using the SendWait method:

Use SendWait to send keystrokes or combinations of keystrokes to the active application and wait for the keystroke messages to be processed.

(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 SendKeys being a horrific way to automate other applications, consider using the automation API instead, and avoid trampling all over the clipboard unless necessary)

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • SendWait function is not available. I am using Visual Studio 2008 with C# .Net 2.0. According to MSDN documentation it is available in .Net 2.0. Am I doing something wrong? – Ali Apr 13 '12 at 07:27
  • `SendWait` has existed in every version of the framework (at least back to 1.1). So, yes, you're doing something wrong, but I can't tell you what. If you just edit `Send` to `SendWait`, and hit compile, what error message do you get? – Damien_The_Unbeliever Apr 13 '12 at 07:28
  • I made a mistake. You are right and the function is available. And it fixed the problem on Windows XP. But now I have another problem and that is if I press F8 quickly many times then the program gives error and shuts down. Only happening on Windows XP. Anyway I will see what I can do about it. – Ali Apr 13 '12 at 07:35