views:

38

answers:

2

I'm using the following code to put the focus on a window (in this case, a notepad window), and sending some key presses to it everytime button 2 is clicked. However, when I press button 2, nothing happens. Can anyone tell my why my sendkeys command is failing?

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    private Process s;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.s = new Process();
        s.StartInfo.FileName = "notepad";
        s.Start();
        s.WaitForInputIdle();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        ShowWindow(s.MainWindowHandle, 1);
        SendKeys.SendWait("Hello");
    }
}
+3  A: 

ShowWindow is showing the started 'Notepad' but not giving it the input focus. Your sendkeys output is being received by form sending it, Form1.

Mitch Wheat
A: 

Well, turns out this was the problem. I wasn't setting the focus to notepad correctly. The command SetForegroundWindow should have been used instead of ShowWindow.

 [DllImport("User32")]
    private static extern int SetForegroundWindow(IntPtr hwnd);

    private Process s;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.s = new Process();
        s.StartInfo.FileName = "notepad";
        s.Start();
        s.WaitForInputIdle();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        //ShowWindow(s.MainWindowHandle, SW_RESTORE);
        SetForegroundWindow(s.MainWindowHandle);
        SendKeys.SendWait("Hello");
    }
}
Waffles