Pergunta

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

Foi útil?

Solução

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.

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top