使用 PowerShell 向窗口控件发送消息
Posted
技术标签:
【中文标题】使用 PowerShell 向窗口控件发送消息【英文标题】:Use PowerShell to send message to a window Control 【发布时间】:2019-09-28 09:39:45 【问题描述】:如何使用powershell向窗口控件发送消息?我有一个C#下的发送示例,但我不知道如何在powershell中编写代码。
//using System.Runtime.InteropServices;
[DllImport("user32.dll", EntryPoint = "SendMessageW", CharSet = CharSet.Unicode)]
internal static extern IntPtr SendMessageS(IntPtr hWnd, int Msg, uint wParam, string lParam);
[DllImport("user32.dll", EntryPoint = "FindWindowW", CharSet = CharSet.Unicode)]
internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
static void TestQm2SendMessage()
var hwnd = FindWindow("QM_Editor", null);
if(hwnd == default(IntPtr)) return;
SendMessageS(hwnd, 12, 1, "Q ' M 'Macro295' C test C#");
我尝试将 C# 代码转换为 powershell 代码,但没有成功。欢迎任何建议
$code = @'
[DllImport("user32.dll", EntryPoint = "SendMessageW", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageS(IntPtr hWnd, int Msg, uint wParam, string lParam);
[DllImport("user32.dll", EntryPoint = "FindWindowW", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
'@
$myAPI = Add-Type -MemberDefinition $code -Name myAPI -PassThru
$myAPI::SendMessageS($myAPI::FindWindow("QM_Editor", $Null), 12, 1, "Q ' M 'Macro295' C test C#");
【问题讨论】:
【参考方案1】:您可以使用.NET System.Windows.Forms.MessageBox。这也适用于 Powershell。
[System.Windows.Forms.MessageBox]::Show("Your message here!", 'This is my title', 'YesNo', 'Information')
【讨论】:
你好,我提到的消息是给控件的,我需要将上面的C#代码转换成powershell代码【参考方案2】:网上找的
function Out-Notepad
param
(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[String]
[AllowEmptyString()]
$Text
)
begin
$sb = New-Object System.Text.StringBuilder
process
$null = $sb.AppendLine($Text)
end
$text = $sb.ToString()
$process = Start-Process notepad -PassThru
$null = $process.WaitForInputIdle()
$sig = '
[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);
'
$type = Add-Type -MemberDefinition $sig -Name APISendMessage -PassThru
$hwnd = $process.MainWindowHandle
[IntPtr]$child = $type::FindWindowEx($hwnd, [IntPtr]::Zero, "Edit", $null)
$null = $type::SendMessage($child, 0x000C, 0, $text)
#Get-Content -Path 'С:\Folder\File.txt' | Out-String | Out-Notepad
'Send this text to Notepad' | Out-Notepad
【讨论】:
以上是关于使用 PowerShell 向窗口控件发送消息的主要内容,如果未能解决你的问题,请参考以下文章
MFC 如何向子窗口发送消息,子窗口是在tab control下的模态窗口?
使用winapi c#向RichEdit控件发送消息时遇到问题
MFC有没有哪几个函数结合起来能做到给一个窗口发键盘消息?比如说向一个窗口发送Ctrl+V?