打开记事本并添加文本无效

时间:2012-07-03 05:02:53

标签: c# winforms .net-2.0

我刚刚从互联网上看到这个片段,但它对我不起作用。 它假设打开一个新的记事本应用程序并在其中添加“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");
}

3 个答案:

答案 0 :(得分:3)

要确保流程已准备好接受输入,请致电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);
}

答案 1 :(得分: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);
        }
    }

答案 2 :(得分: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");
        }