2009-02-07 20 views
24

Tôi đang cố gắng sử dụng SendMessage để Notepad, để tôi có thể chèn văn bản bằng văn bản mà không cần làm cho Notepad cửa sổ hoạt động.Làm thế nào để gửi văn bản vào Notepad trong C#/Win32?

Tôi đã làm điều gì đó như thế này trong quá khứ bằng cách sử dụng SendText, nhưng điều đó bắt buộc phải tập trung vào Notepad.

Bây giờ, lần đầu tiên tôi lấy tay cầm Windows:

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

Tôi đã xác nhận đó là xử lý phù hợp với Notepad, cùng hiển thị trong Windows Task Manager.

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

Từ đây, tôi không thể yêu cầu SendMessage làm việc trong tất cả thử nghiệm của mình. Tôi có đi sai hướng không?

Trả lời

35
[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

6

Trước tiên, bạn phải tìm cửa sổ con nơi nhập văn bản. Bạn có thể làm điều này bằng cách tìm cửa sổ con với lớp cửa sổ "Chỉnh sửa". Khi bạn có tay cầm cửa sổ đó, hãy sử dụng WM_GETTEXT để nhận văn bản đã nhập, sau đó sửa đổi văn bản đó (ví dụ: thêm văn bản của riêng bạn), sau đó sử dụng WM_SETTEXT để gửi lại văn bản đã sửa đổi.

0
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); 
    } 
} 
Các vấn đề liên quan