如何在C#/Win32中将文本发送到记事本?

33

我试图使用SendMessage将文本插入到记事本中,而不使记事本成为活动窗口。

过去我曾经尝试过使用SendText实现这个功能,但那需要让记事本获得焦点。

现在,首先我正在检索Windows句柄:

Process[] processes = Process.GetProcessesByName("notepad");
Console.WriteLine(processes[0].MainWindowHandle.ToString());
我确认这是记事本的正确句柄,与在“Windows任务管理器”中显示的相同。
[DllImport("User32.dll", EntryPoint = "SendMessage")]
public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);

从这里开始,我一直没有成功地让SendMessage在我的所有尝试中工作。 我是不是走错了方向?

3个回答

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

WM_SETTEXT=0x000c


4
使用这个函数确实很奇怪,它会将窗口的名称更改为“textBox11.Text”,但并不像键盘消息一样发送实际消息 :/ - Michael Longhurst

7

首先,您需要找到输入文本的子窗口。您可以通过查找窗口类为“Edit”的子窗口来实现。 一旦您获得了该窗口句柄,使用WM_GETTEXT获取已输入的文本,然后修改该文本(例如添加自己的文本),然后使用WM_SETTEXT将修改后的文本发送回去。


4
using System.Diagnostics;
using System.Runtime.InteropServices;

static class Notepad
{
    #region Imports
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

    [DllImport("User32.dll")]
    private static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);

    //this is a constant indicating the window that we want to send a text message
    const int WM_SETTEXT = 0X000C;
    #endregion


    public static void SendText(string text)
    {
        Process notepad = Process.Start(@"notepad.exe");
        System.Threading.Thread.Sleep(50);
        IntPtr notepadTextbox = FindWindowEx(notepad.MainWindowHandle, IntPtr.Zero, "Edit", null);
        SendMessage(notepadTextbox, WM_SETTEXT, 0, text);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接