Hi objecref,
The problem I believe is that the Notepad is not the active application. How
I said there is only one focused window at a time and it is or it is a child
to the foreground (active) window. If you try GetFocus for a thread which
hasn't created the foreground window it always return null.
Just a little reminder. Even though you can post key messages to a window it
is not guarantee that the target window will accept them correctly. Each
input (UI) thread has associated keystate buffers and so on that play some
role in the key processing. If you just post key messages it won't go thru
all the internal key processing and won't update those structures. Methods
like GetKeyState, GetAsyncKeyState, GetKeyboardState and so on which
application use won't work. Key messages are only notifications aftere all
the work of precessing the keyboard is done. The only way to simulate real
keyboard activity is to use either SendInput or keybd_event API or SendKeys
class in .NET.
However because they synthesizes keyboard strokes, mouse movements and mouse
button clicks it you cannot specify the target window. Keystorkes go to the
focused window, mouse events go to the window under the mouse cursor
position.
Anyways if you still want to use post messages you may consider using
AttachThreadInput and SetKeyboardState method to handle some of the
situations. However some keys such as CapsLock, NumLock, etc cannot be
simulated unless SendInput or keybd_event are used.
--
HTH
Stoitcho Goutsev (100) [C# MVP]
objectref said:
Hmmmm....
at first, thanks for your solution, it seems than know i am close enough,
but:
Let's assume that, for simplicity reasons, i want to test your code with a
pre-known
window handle. I take this from enumerating processes, find, let's say an
open Notepad window
and then get it's MainWindowHandle, that is, 3475108.
But, the below code does not work. It reaches the "PostMessage"line but
i
do
not
get an Enter hit in notepad app.
Can you figure out why ?
private void button1_Click(object sender, System.EventArgs e)
{
IntPtr thisThreadID = new IntPtr(AppDomain.GetCurrentThreadId());
IntPtr activeHwnd = GetForegroundWindow();
if (activeHwnd != IntPtr.Zero)
{
IntPtr activeThreadID = GetWindowThreadProcessId((IntPtr) 3475108,
IntPtr.Zero);
if (AttachThreadInput(activeThreadID, thisThreadID, true))
{
IntPtr focusedHwnd = GetFocus();
if (focusedHwnd != IntPtr.Zero)
{
//Console.WriteLine("FocusedHwnd: {0}\n====",
focusedHwnd.ToString());
listBox1.Items.Add("FocusedHwnd: {0}\n====" +
focusedHwnd.ToString());
PostMessage((IntPtr) focusedHwnd, WM_CHAR, 13, 0);
}
AttachThreadInput(activeThreadID, thisThreadID, false);
}
}
}