【问题标题】:How to use SendMessage to paste something to a different window如何使用 SendMessage 将内容粘贴到不同的窗口
【发布时间】:2013-06-23 13:28:33
【问题描述】:

我正在使用以下 SendMessage 函数将文本发送/粘贴到不同的应用程序。 但在那个函数中,我必须从另一个应用程序中给出窗口的名称。

如何更改它以获取当前活动窗口并将代码粘贴到那里?

代码:

[DllImport("user32.dll")]  
public static extern int SendMessage(int hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPStr)] string lParam);  

[DllImport("user32.dll", SetLastError = true)]  
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  

[DllImport("user32.dll", SetLastError = true)]  
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

public const int WM_PASTE = 0x0302;

IntPtr windowHandle = FindWindow("NOTEPAD", null);  
IntPtr editHandle = FindWindowEx(windowHandle, IntPtr.Zero, "EDIT", null);  
string textToSendToFile = "Input here your text";
Clipboard.SetText("Test");
SendMessage((int)editHandle, WM_PASTE, 0, textToSendToFile); 

我也得到了这个,但我真的不知道如何将它与上面的代码结合起来......

[DllImportAttribute("user32.dll", EntryPoint = "GetForegroundWindow")]
public static extern IntPtr GetForegroundWindow();

[DllImportAttribute("user32.dll", EntryPoint = "GetWindowThreadProcessId")]
public static extern uint GetWindowThreadProcessId([InAttribute()] IntPtr hWnd, IntPtr lpdwProcessId);

IntPtr hWndForegroundWindow = GetForegroundWindow();
uint activeThreadID = GetWindowThreadProcessId(hWndForegroundWindow, IntPtr.Zero);

【问题讨论】:

    标签: c# .net sendmessage


    【解决方案1】:

    WM_PASTE 消息不使用参数。这只是指示收件人获取剪贴板的内容并粘贴它们。因此,如果您希望收件人做任何事情,您需要先填充剪贴板。

    如果您不希望污染剪贴板,并且不应该因为它属于用户,那么您可以发送一个 EM_REPLACESEL 消息传递 lParam 中的文本。

    如果要查找用户当前正在处理的窗口,请使用 GetForegroundWindow。

    但是,最好使用自动化 API,而不是伪造低级消息。

    【讨论】:

    • 也许我把我的问题解释错了对不起。因为如果你有一个打开的记事本,上面的代码已经可以工作了。但我喜欢让它在任何打开的窗口(当前窗口)上工作,而不是只用记事本......我喜欢有一个在后台运行的小应用程序,如果你按下快捷方式,它应该在活动窗口中粘贴一些文本.
    • 我在解释您对 WM_PASTE 的使用不正确。您正在寻找的窗口是 GetForegroundWindow。但自动化 API 才是您真正想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多