Reputation: 13649
I just saw this snippet from the internet but it doesn't work from me. It's suppose to open a new notepad application and add "asdf" into it.
Is there any wrong on the code?
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, [MarshalAs(UnmanagedType.LPStr)] string lParam);
void Test()
{
const int WM_SETTEXT = 0x000C;
ProcessStartInfo startInfo = new ProcessStartInfo("notepad.exe");
startInfo.UseShellExecute = false;
Process notepad = System.Diagnostics.Process.Start(startInfo);
SendMessage(notepad.MainWindowHandle, WM_SETTEXT, 0, "asdf");
}
Upvotes: 1
Views: 4815
Reputation: 1767
To make sure that process is ready to accept input, call notepad.WaitForInputIdle()
. And it is important to use MainWindowHandle
of the process that was just created, not the any notepad process.
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
static void ExportToNotepad(string text)
{
ProcessStartInfo startInfo = new ProcessStartInfo("notepad");
startInfo.UseShellExecute = false;
Process notepad = Process.Start(startInfo);
notepad.WaitForInputIdle();
IntPtr child = FindWindowEx(notepad.MainWindowHandle, new IntPtr(0), null, null);
SendMessage(child, 0x000c, 0, text);
}
Upvotes: 4
Reputation: 10153
try this:
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
void Test()
{
ProcessStartInfo startInfo = new ProcessStartInfo("notepad.exe");
startInfo.UseShellExecute = false;
Process notepad = System.Diagnostics.Process.Start(startInfo);
//Wait Until Notpad Opened
Thread.Sleep(100);
Process[] notepads = Process.GetProcessesByName("notepad");
IntPtr child = FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null);
SendMessage(child, 0x000c, 0, "test");
}
Upvotes: 0
Reputation: 6490
Following Code will do the trick for you,
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
private void button1_Click(object sender, EventArgs e)
{
Process [] notepads=Process.GetProcessesByName("notepad");
if(notepads.Length==0)return;
if (notepads[0] != null)
{
IntPtr child= FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null);
SendMessage(child, 0x000C, 0, textBox1.Text);
}
}
Upvotes: 0