tags:

views:

197

answers:

1

Hello, I have been searching for a working example on how to accomplish this, but no luck so far.

This is what I have right now :

 [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr
        wParam, IntPtr lParam);

Process[] processlist = Process.GetProcesses();

            foreach (Process p in processlist)
            {
                if (p.ProcessName == "notepad")
                {
                    //MessageBox.Show("bu");
                    /*

                    LRESULT PostMessage( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);

                    WM_KEYDOWN
                           WPARAM wParam
                            LPARAM lParam;
                    Parameters
                        wParam
                            Specifies the virtual-key code of the nonsystem key. 
                        lParam
                            Specifies the repeat count, scan code, extended-key flag, 
                            context code, previous key-state flag, and transition-state flag, 
                            as shown in this table.

                    ......So......

                    LRESULT debugvalue = PostMessage( Handle_to_where_the_message_is_going,
                                                      WM_KEYDOWN, (WPARAM)VK_ENTER, (LPARAM)0)


                     */
                    uint WM_KEYDOWN = 0x0100;
                    PostMessage(p.Handle, WM_KEYDOWN, Marshal.StringToHGlobalAuto("something"), IntPtr.Zero);
                }
            }

Now, what am I doing wrong?

http://msdn.microsoft.com/en-us/library/ms646280%28VS.85%29.aspx May be of assistance

+2  A: 

Lots of things wrong. You are sending the message to the Process.Handle instead of the window handle. Use at least Process.MainWindowHandle. Also, you should send a virtual keystroke, not a string. The Keys enumeration gets you the key codes. Sending a string requires a keystroke for each letter in the string. Also, you should send the WM_KEYUP message as well. Also, the receiving application is likely to use the keyboard state to determine whether the Shift, Ctrl or Alt keys are down and translate the keystroke to a typing key accordingly. You can't fake that with PostMessage().

That ought to get it somewhat working. To make it truly reliable, I think you need a WH_JOURNALPLAYBACK hook, set by SetWindowsHookEx(). You can't write that in C#, it doesn't support injecting DLLs into another process. Check out what AutoHotkey can do for you.

Hans Passant