【问题标题】:How to send text to Notepad in C#/Win32?如何在 C#/Win32 中向记事本发送文本?
【发布时间】:2010-10-06 02:56:13
【问题描述】:

我正在尝试使用 SendMessage 到记事本,这样我就可以在不使记事本成为活动窗口的情况下插入书面文本。

我过去曾使用SendText 做过类似的事情,但这需要让记事本获得焦点。

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

Process[] processes = Process.GetProcessesByName("notepad");
Console.WriteLine(processes[0].MainWindowHandle.ToString());

我已经确认它是记事本的正确手柄,与Windows Task Manager 中显示的相同。

[DllImport("User32.dll", EntryPoint = "SendMessage")]
public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);

从这里开始,我无法让 SendMessage 在我的所有实验中工作。我是不是走错方向了?

【问题讨论】:

    标签: c# winapi


    【解决方案1】:
        [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

    【讨论】:

    • 所以这真的很奇怪,使用这个函数将窗口的名称更改为textBox11.Text。它实际上并没有像键盘消息一样发送消息:/
    【解决方案2】:

    您首先必须找到输入文本的子窗口。您可以通过查找具有窗口类“编辑”的子窗口来完成此操作。 获得窗口句柄后,使用 WM_GETTEXT 获取已输入的文本,然后修改该文本(例如,添加您自己的),然后使用 WM_SETTEXT 将修改后的文本发回。

    【讨论】:

      【解决方案3】:
      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);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多