Keith - Dave's Blog

Search
My timeline on Mastodon

WinRT Toast from PowerShell

2016 Jun 15, 3:54

I've made a PowerShell script to show system toast notifications with WinRT and PowerShell. Along the way I learned several interesting things.

First off calling WinRT from PowerShell involves a strange syntax. If you want to use a class you write [-Class-,-Namespace-,ContentType=WindowsRuntime] first to tell PowerShell about the type. For example here I create a ToastNotification object:

[void][Windows.UI.Notifications.ToastNotification,Windows.UI.Notifications,ContentType=WindowsRuntime];
$toast = New-Object Windows.UI.Notifications.ToastNotification -ArgumentList $xml;
And here I call the static method CreateToastNotifier on the ToastNotificationManager class:
[void][Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime];
$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($AppUserModelId);
With this I can call WinRT methods and this is enough to show a toast but to handle the click requires a little more work.

To handle the user clicking on the toast I need to listen to the Activated event on the Toast object. However Register-ObjectEvent doesn't handle WinRT events. To work around this I created a .NET event wrapper class to turn the WinRT event into a .NET event that Register-ObjectEvent can handle. This is based on Keith Hill's blog post on calling WinRT async methods in PowerShell. With the event wrapper class I can run the following to subscribe to the event:

function WrapToastEvent {
param($target, $eventName);

Add-Type -Path (Join-Path $myPath "PoshWinRT.dll")
$wrapper = new-object "PoshWinRT.EventWrapper[Windows.UI.Notifications.ToastNotification,System.Object]";
$wrapper.Register($target, $eventName);
}

[void](Register-ObjectEvent -InputObject (WrapToastEvent $toast "Activated") -EventName FireEvent -Action {
...
});

To handle the Activated event I want to put focus back on the PowerShell window that created the toast. To do this I need to call the Win32 function SetForegroundWindow. Doing so from PowerShell is surprisingly easy. First you must tell PowerShell about the function:

Add-Type @"
using System;
using System.Runtime.InteropServices;
public class PInvoke {
[DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hwnd);
}
"@
Then to call:
[PInvoke]::SetForegroundWindow((Get-Process -id $myWindowPid).MainWindowHandle);

But figuring out the HWND to give to SetForegroundWindow isn't totally straight forward. Get-Process exposes a MainWindowHandle property but if you start a cmd.exe prompt and then run PowerShell inside of that, the PowerShell process has 0 for its MainWindowHandle property. We must follow up process parents until we find one with a MainWindowHandle:

$myWindowPid = $pid;
while ($myWindowPid -gt 0 -and (Get-Process -id $myWindowPid).MainWindowHandle -eq 0) {
$myWindowPid = (gwmi Win32_Process -filter "processid = $($myWindowPid)" | select ParentProcessId).ParentProcessId;
}
PermalinkComments.net c# powershell toast winrt

Golf

2010 Nov 18, 2:58PermalinkCommentsComics Andy Keith technical

Area Man Suddenly Realizes He's The One Who's Been Killing Off World's Bee Population | The Onion - America's Finest News Source

2010 Sep 8, 2:16'Following a news update on the depopulation of honeybees across North America and much of the world, it suddenly dawned on local bank teller Keith Orlander Tuesday that he, personally, was responsible for the dramatic and theretofore unexplained disappearance of the insects. "Boy, come to think of it, I guess I have been killing millions of bees lately,"'PermalinkCommentsbee bees humor onion

Wp64 Issues

2007 Aug 6, 3:43Miladin told me about the Visual Studio compiler's promising option Wp64 that finds 64bit portability issues when compiling in 32bit. If, for instance, you cast from a (long*) to a (long) you get a W4 warning. However, the #defines are still set for 32bit builds. This means that other parts of the code can make assumptions based on the #defines that are valid on 32bit but generate 64bit errors or warnings.

For instance, in winuser.h the public published Windows header file there's the following:
...
#ifdef _WIN64
...
WINUSERAPI
LONG_PTR
WINAPI
SetWindowLongPtrA(
    __in HWND hWnd,
    __in int nIndex,
    __in LONG_PTR dwNewLong);
...
#else  /* _WIN64 */
...
#define SetWindowLongPtrA   SetWindowLongA
...
#endif /* _WIN64 */
...
In 64bit everything's normal but in 32bit SetWindowLongPtrA is #defined to SetWindowLongA which takes a LONG rather than a LONG_PTR. So take the following code snippet:
...
LONG_PTR inputValue = 0;
LONG_PTR error = SetWindowLongPtrA(hWnd, nIndex, inputValue);
...
This looks fine but generates warnings with the Wp64 flag.

In 64 bit, p is cast to (LONG_PTR) and that's great because we're actually calling SetWindowLongPtrA which takes a LONG_PTR. In 32 bit, p is cast to (LONG_PTR) which is then implicitly cast to (LONG) because we're actually calling SetWindowLongA. LONG and LONG_PTR are the same size in 32bit which is fine but if you turn on the Wp64 flag there's a W4 warning because of the implicit cast from a larger size to a smaller size if you were to compile for 64bit. So even though doing a 32bit or 64bit compile would have worked just fine, if you turn on the Wp64 flag for 32bit you'd get an error here.

It looks like I'm the most recent in a list of people to notice this issue. Well I investigated this so... I'm blogging about it too!PermalinkCommentswp64 technical 64bit compiler c++ visual-studio setwindowlongptra
Older Entries Creative Commons License Some rights reserved.