1

我刚刚从互联网上看到了这个片段,但它对我不起作用。假设打开一个新的记事本应用程序并在其中添加“asdf”。

代码有什么错误吗?

[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");
}
4

3 回答 3

4

要确保该进程已准备好接受输入,请调用notepad.WaitForInputIdle(). 重要的是使用MainWindowHandle刚刚创建的进程,而不是任何记事本进程。

[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);
}
于 2015-05-13T15:45:00.987 回答
0

以下代码将为您解决问题,

[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);
        }
    }
于 2012-07-03T05:31:37.057 回答
0

尝试这个:

    [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");
        }
于 2012-07-03T05:45:29.990 回答