web-dev-qa-db-ja.com

C#/ Win32でメモ帳にテキストを送信する方法は?

SendMessage to Notepadを使用して、メモ帳をアクティブウィンドウにせずにテキストを挿入できるようにしています。

私は過去に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を機能させることができませんでした。私は間違った方向に進んでいますか?

31
lolcat
    [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

45
ebattulga

まず、テキストを入力する子ウィンドウを見つける必要があります。これは、ウィンドウクラス「編集」で子ウィンドウを見つけることで実行できます。ウィンドウハンドルを取得したら、WM_GETTEXTを使用して既に入力されているテキストを取得し、そのテキストを変更(たとえば、独自のテキストを追加)してから、WM_SETTEXTを使用して変更したテキストを送り返します。

6
Stefan
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);
    }
}
3
Brian