3

My target is to send keyboard events to external application. From my application, I'm launching a C# console application that bring the target application to the front and uses SendKeys.SendWait to send keyboards events. I ran into a rate case where the command doesn't have any affect.

When debugging it, it works but when running it not in debug it fails. I think it as something to do with the fact that when debugging my application is the active application.

Mustafa Özçetin
  • 1,893
  • 1
  • 14
  • 16
Guy
  • 325
  • 2
  • 6
  • 14
  • 1
    accept some answers, and people might be more willing to help.... – Mitch Wheat May 16 '10 at 07:28
  • You are right I wasn't aware of it I just used the useful buttons. But now I accepted all of my questions. Thanks, – Guy May 16 '10 at 08:01
  • I check it with the spy++ and got the following deference: 007F02C6 S WM_ACTIVATE fActive:WA_INACTIVE fMinimized:False hwndPrevious:(null) 007F02C6 S message:0xC3DA [Registered:"SunAwtComponent"] wParam:00000000 lParam:00000000 007F02C6 R message:0xC3DA [Registered:"SunAwtComponent"] lResult:00000001 007F02C6 R WM_ACTIVATE – Guy May 16 '10 at 16:46
  • Visual Basic has the AppActivate call – Drew LeSueur Aug 04 '11 at 04:57
  • Does this answer your question? [C# SendKeys.SendWait() doesn't always work](https://stackoverflow.com/questions/17069123/c-sharp-sendkeys-sendwait-doesnt-always-work) – Vinod Srivastav Apr 15 '23 at 05:15

3 Answers3

2

You'll need to do a little work, and it changes depending on the version of Windows. There's an MSDN page that has a good explanation and an example:

http://msdn.microsoft.com/en-us/library/ms171548.aspx

philiphobgen
  • 2,234
  • 17
  • 28
  • Thanks for the link. I don't understand what should I do I'm using sendWait run with .NET Framework 3.0 and experiencing the problem. – Guy May 16 '10 at 10:58
  • 1
    Read everything on that page from "Simulating Keyboard Input" down. There's a section titled "To send a keystroke to a different application" it shows an example of sending key to another application using sendWait. You need to read it all though, as it points out issues that you might get. – philiphobgen May 16 '10 at 15:55
  • Like stated in the answer, it also depends upon the version of .NET framework being used. It worked for me on .NET 4.5 but didn't work on .NET 4.5.3. – Abhishek Dec 02 '17 at 15:01
0

You can try this, it works for me.

var text = "Hello";
var target = Keyboard.FocusedElement;
var routedEvent = TextCompositionManager.TextInputEvent;
target.RaiseEvent( new TextCompositionEventArgs( InputManager.Current.PrimaryKeyboardDevice, 
new TextComposition(InputManager.Current, target, text)) { RoutedEvent = routedEvent });

https://stackoverflow.com/a/1646568

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

Maybe you should run your program as an administrator. At least, it works for me in some cases.

Pop Young
  • 11
  • 3