Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SendMessage is causing script to hang

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

like image 653
yaodin Avatar asked Mar 27 '12 14:03

yaodin


1 Answers

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.

like image 175
Andrey Avatar answered Oct 11 '22 13:10

Andrey