SendMessage is causing script to hang

流过昼夜 提交于 2019-12-12 07:19:17

问题


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

or

Remove-job -name offmon -force

will not kill it. With out the force on remove-job it reports it cannot kill it because it is not finished.

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}

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.

Thanks!

Edit: Typos


回答1:


Change SendMessage to PostMessage. It worked for me.

The difference is that PostMessage is asynchronous and it doesn't have to wait for any response.




回答2:


Short version of this script as a batch file command (put this line in a .bat file):

@powershell (Add-Type '[DllImport(\"user32.dll\")]^public static extern int PostMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::PostMessage(-1,0x0112,0xF170,2)




回答3:


Please add

Add-Type -Assembly UIAutomationClient

and use

public static extern IntPtr PostMessage(int hWnd, UInt32 hMsg, Int32 wParam, Int32 lParam);

or

public static extern IntPtr SendMessage(int hWnd, UInt32 hMsg, Int32 wParam, Int32 lParam);

And the script will no longer crash



来源:https://stackoverflow.com/questions/9891585/sendmessage-is-causing-script-to-hang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!