Question:
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.
1 2 |
Stop-job -name offmon |
or
1 2 |
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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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
Answer:
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.