1

Im playing around in C# and want my little console program to spell my name in a notepad window I have open. I've got the window handle (IntPtr) but don't really know what to do from here.

I could use SendKey but I want it to work whenever the notepad has focus or not, and as I understand it Senkey only work if you have the windowed focused :(

EDIT: I've tried the following (trying to simulate pressing B):

PostMessage(NotepadWindowHandle, 0x100, 0x42, 0);
Thread.Sleep(1000);
PostMessage(NotepadWindowHandle, 0x101, 0x42, 0);

Nothing happens :( And it does not break

Jason94
  • 13,320
  • 37
  • 106
  • 184
  • You can also look into this post: http://stackoverflow.com/questions/1922707/setting-external-application-focus Its VB but should help. – Nick Sinas May 08 '12 at 16:54

2 Answers2

2

You are correct, SendKey only works for focused windows.

What you want to do is P/Invoke SendMessage and send WM_SETTEXT on the text box's handle (note that that's not the main window handle!). To get it you navigate down the window hierarchy until you reach it with GetWindow.

As a freebie, to get the text box's handle, simply call GetWindow with GW_CHILD on your main Notepad window handle and you'll get it, it's literally the first child.

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
Blindy
  • 65,249
  • 10
  • 91
  • 131
  • Although note that this doesn't *type* the text. It'll only work for windows that understand WM_SETTEXT. – Roger Lipscombe May 08 '12 at 16:56
  • Which the Notepad window does. – Blindy May 08 '12 at 16:57
  • ...which the Notepad window does. Because it's an EDIT control. I believe that RichText windows will work, so WordPad's OK too. I'm just making the point that it's not *typing* the text, so it might not work with other text entry fields. – Roger Lipscombe May 08 '12 at 18:44
0

If you have Notepad’s window handle, why don’t you first activate it as the foreground window and then issue your SendKey?

This is the P/Invoke signature for setting a window as the foreground window:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

Edit: Former answer for a similar issue: https://stackoverflow.com/a/8953524/1149773

Community
  • 1
  • 1
Douglas
  • 53,759
  • 13
  • 140
  • 188