SendMessage causes the script to hang

I had a problem when the SendMessage () function causes the script to hang and therefore never quits, despite the fact that it starts SendMessage as it should (its task is completed). Is there anyway to get around this because I'm scooping up time by killing it from a script wizard.

Stop-job -name offmon 

or

 Remove-job -name offmon -force 

won't kill him. Due to the strength on remove-job, he reports that he cannot kill him because he is not finished.

I need to call it many times a day, and every time I do this, a new powershell.exe file appears, which contains about 30 MB of memory.

Note. The coding of your monitors will be displayed if you run it, and "@ should be at the beginning of the line (cannot display it to look good).

 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} 

It also freezes in exactly the same way without start-job, so I do not believe that this is due to start-job makes scripts hang. MS support . Next up is Win7Ent / 2008R2.

Thanks!

Edit: Typos

+4
source share
2 answers

Change SendMessage to PostMessage . It worked for me.

The difference is that PostMessage asynchronous and it does not need to wait for a response.

+3
source

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 break

0
source

Source: https://habr.com/ru/post/1403680/


All Articles