SendMessage 导致脚本挂起 [英] SendMessage is causing script to hang
问题描述
我遇到了一个问题,即 SendMessage() 函数导致脚本挂起,因此虽然它正在像它应该的那样运行 SendMessage(它的任务完成)但永远不会退出.有没有办法解决这个问题,因为我有一段时间从主脚本中杀死它.
I am having an issue where the SendMessage() function is causing a script to hang and thus never exiting though it is running the SendMessage like it should (Its task completes). Is there anyway to get around this because I am having a heck of a time killing it from the master script.
Stop-job -name offmon
或
Remove-job -name offmon -force
不会杀死它.如果没有对 remove-job 施加强制力,它报告说它无法杀死它,因为它还没有完成.
will not kill it. With out the force on remove-job it reports it cannot kill it because it is not finished.
我每天需要多次调用此方法,每次调用都会生成一个新的 powershell.exe,占用大约 30M 的内存.
I need to call this many times per day and each time I do it spawns a new powershell.exe eating about 30M of memory.
注意:如果您运行该代码,代码将关闭您的显示器,并且@"需要位于行首(不能将其标记为好看).
Note: The code will turn of your monitors if you run it and the "@ needs to be at the beginning of the line (can't tab it over to look nice).
start-job -Name offmon -ScriptBlock {
$HWND = -1
$WM_SYSCOMMAND = 0x0112
$SC_MONITORPOWER = 0xF170
$MONITOR_ON = -1
$MONITOR_OFF = 2
#Store the C# signature of the SendMessage function.
$signature = @"
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
"@
#Add the SendMessage function as a static method of a class
$SendMessage = Add-Type -MemberDefinition $signature -Name "Win32SendMessage" -Namespace Win32Functions -PassThru
#Invoke the SendMessage Function
$SendMessage::SendMessage($HWND, $WM_SYSCOMMAND, $SC_MONITORPOWER, $MONITOR_OFF)
exit}
此外,如果没有启动作业,这也会挂起,所以我认为它与 start-job 导致脚本挂起. MS 支持.此外,这是 Win7Ent/2008R2.
Also this hangs just the same without start-job so I do not believe it is related to start-job causes scripts to hang. MS Support. Further this is Win7Ent/2008R2.
谢谢!
错别字
推荐答案
将 SendMessage
更改为 PostMessage
.它对我有用.
Change SendMessage
to PostMessage
. It worked for me.
区别在于 PostMessage
是异步,不需要等待任何响应.
The difference is that PostMessage
is asynchronous and it doesn't have to wait for any response.
这篇关于SendMessage 导致脚本挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!