0

How can I simulate a foreign window as the focused window? I need this, because I want to send keys to the notepad window and it only works if the notepad window has the focus. But I don't want to loose the focus on my own window.

public IntPtr Find(string taskName, string windowName)
{
    return Fenster.FindWindow(taskName, windowName);
}
public void Send(IntPtr hwnd, string text)
{
    if (!hwnd.Equals(IntPtr.Zero))
    {
        SendKeys.Send(text);
    }
}
public bool SetForeground(IntPtr hwnd)
{
    return SetForegroundWindow(hwnd);   
}

[DllImport("user32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lp1, string lp2);

[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);

Thanks a lot!

Thomas
  • 2,093
  • 3
  • 21
  • 40
  • You can't, or at least you don't want to. Send the proper messages to Notepad, don't use SendKeys. – CodeCaster Sep 23 '14 at 11:25
  • is there another way to send keys not using Sendkeys? – Thomas Sep 23 '14 at 11:27
  • Now you're asking the right question. See duplicate. :) Using `SendMessage()` you can [send a `WM_CHAR` message to a window's message queue](http://stackoverflow.com/questions/13514820/sendmessage-when-to-use-keydown-syskeydown-etc), simulating keypresses to a window that doesn't have focus. – CodeCaster Sep 23 '14 at 11:30

1 Answers1

1

The best solution would be to get the HWND of the window that you want to control and send the key message (either WM_KEY_DOWN and WM_KEY_UP or WM_CHAR - may depend on Application and purpose) directly via SendMessage or PostMessage.

vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80