c# - 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

JavaScript Types and WinRT Types

2016 Jan 21, 5:35PermalinkCommentschakra development javascript winrt

harmony:generators [ES Wiki]

2013 Dec 17, 9:01

Adds the yield keyword enabling you to write JS code that sort of looks like C# await.

Overview

First-class coroutines, represented as objects encapsulating suspended execution contexts (i.e., function activations). Prior art: Python, Icon, Lua, Scheme, Smalltalk.

PermalinkCommentstechnical javascript

URI functions in Windows Store Applications

2013 Jul 25, 1:00PermalinkCommentsc# c++ javascript technical uri windows windows-runtime windows-store

ILSpy - SharpDevelop Wiki

2011 Mar 28, 4:06"ILSpy is the open-source .NET assembly browser and decompiler. Development started after Red Gate announced that the free version of .NET Reflector would cease to exist by end of February 2011."PermalinkComments.net tools reflector c# development csharp dotnet technical tool

Windows 7 Accelerator Platform COM / C# Interop

2010 Aug 20, 11:20

For a new project I'm working on involving IE's installed Accelerators and OpenSearch search providers via the Windows 7 Accelerator Platform, I've created a C#/COM interop class for those APIs.

Download the osinterop.cs interop file here.

PermalinkCommentstechnical accelerator csharp com

pinvoke.net: ConsoleFunctions (kernel32)

2010 Aug 14, 5:34pInvoke.net is a wiki for the C# interop declarations for various Win32 functions.PermalinkCommentspinvoke c# csharp consle api windows reference wiki technical

Coding4Fun : Look at me! Windows Image Acquisition

2009 Jun 20, 9:43How to use the WIA APIs in C#. WIA is Windows API to get images from scanners and cameras. And, as I found out, if you want to use the API in PowerShell try '$deviceManager = new-object -ComObject WIA.DeviceManager'PermalinkCommentsvideo scanner api wia csharp howto programming camera image photo .net webcam technical

Free OCR software? You may already have it... - Jon Galloway

2009 Jun 20, 9:39If you have Office installed you may have an OCR library sitting on your hard drive just waiting to be used via C#...PermalinkCommentsocr microsoft office .net automation scanner camera windows technical

A Brief History of Microsoft's Live Search's New Domain Bing

2009 Jun 1, 11:07
Logo for bing! from 2003 via The Wayback MachineLogo for BING* from 2006 via The Wayback MachineKimberly Saia's flickr photo of the Microsoft bing search logo.
When I heard that Live Search is now Bing one of my initial thoughts was how'd they get that domain name given the unavailability of pronouncable four letter .COM domain names. Well, the names been used in the past. Here now, via the Wayback Machine is a brief, somewhat speculative, and ultimately anticlimactic history of bing.com:

The new name reminds me of the show Friends. Also, I hope they get a new favicon - I don't enjoy the stretched 'b' nor its color scheme.

PermalinkCommentsmicrosoft technical domain history search archive dns bing

Tab Expansion in PowerShell

2008 Nov 18, 6:38

PowerShell gives us a real CLI for Windows based around .Net stuff. I don't like the creation of a new shell language but I suppose it makes sense given that they want something C# like but not C# exactly since that's much to verbose and strict for a CLI. One of the functions you can override is the TabExpansion function which is used when you tab complete commands. I really like this and so I've added on to the standard implementation to support replacing a variable name with its value, tab completion of available commands, previous command history, and drive names (there not restricted to just one letter in PS).

Learning the new language was a bit of a chore but MSDN helped. A couple of things to note, a statement that has a return value that you don't do anything with is implicitly the return value for the current function. That's why there's no explicit return's in my TabExpansion function. Also, if you're TabExpansion function fails or returns nothing then the builtin TabExpansion function runs which does just filenames. This is why you can see that the standard TabExpansion function doesn't handle normal filenames: it does extra stuff (like method and property completion on variables that represent .Net objects) but if there's no fancy extra stuff to be done it lets the builtin one take a crack.

Here's my TabExpansion function. Probably has bugs, so watch out!


function EscapePath([string] $path, [string] $original)
{
    if ($path.Contains(' ') -and !$original.Contains(' '))
    {
        '"'   $path   '"';
    }
    else
    {
        $path;
    }
}

function PathRelativeTo($pathDest, $pathCurrent)
{
    if ($pathDest.PSParentPath.ToString().EndsWith($pathCurrent.Path))
    {
        '.\'   $pathDest.name;
    }
    else
    {
        $pathDest.FullName;
    }
}

#  This is the default function to use for tab expansion. It handles simple
# member expansion on variables, variable name expansion and parameter completion
# on commands. It doesn't understand strings so strings containing ; | ( or { may
# cause expansion to fail.

function TabExpansion($line, $lastWord)
{
    switch -regex ($lastWord)
    {
         # Handle property and method expansion...
         '(^.*)(\$(\w|\.) )\.(\w*)$' {
             $method = [Management.Automation.PSMemberTypes] `
                 'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
             $base = $matches[1]
             $expression = $matches[2]
             Invoke-Expression ('$val='   $expression)
             $pat = $matches[4]   '*'
             Get-Member -inputobject $val $pat | sort membertype,name |
                 where { $_.name -notmatch '^[gs]et_'} |
                 foreach {
                     if ($_.MemberType -band $method)
                     {
                         # Return a method...
                         $base   $expression   '.'   $_.name   '('
                     }
                     else {
                         # Return a property...
                         $base   $expression   '.'   $_.name
                     }
                 }
             break;
          }

         # Handle variable name expansion...
         '(^.*\$)([\w\:]*)$' {
             $prefix = $matches[1]
             $varName = $matches[2]
             foreach ($v in Get-Childitem ('variable:'   $varName   '*'))
             {
                 if ($v.name -eq $varName)
                 {
                     $v.value
                 }
                 else
                 {
                    $prefix   $v.name
                 }
             }
             break;
         }

         # Do completion on parameters...
         '^-([\w0-9]*)' {
             $pat = $matches[1]   '*'

             # extract the command name from the string
             # first split the string into statements and pipeline elements
             # This doesn't handle strings however.
             $cmdlet = [regex]::Split($line, '[|;]')[-1]

             #  Extract the trailing unclosed block e.g. ls | foreach { cp
             if ($cmdlet -match '\{([^\{\}]*)$')
             {
                 $cmdlet = $matches[1]
             }

             # Extract the longest unclosed parenthetical expression...
             if ($cmdlet -match '\(([^()]*)$')
             {
                 $cmdlet = $matches[1]
             }

             # take the first space separated token of the remaining string
             # as the command to look up. Trim any leading or trailing spaces
             # so you don't get leading empty elements.
             $cmdlet = $cmdlet.Trim().Split()[0]

             # now get the info object for it...
             $cmdlet = @(Get-Command -type 'cmdlet,alias' $cmdlet)[0]

             # loop resolving aliases...
             while ($cmdlet.CommandType -eq 'alias') {
                 $cmdlet = @(Get-Command -type 'cmdlet,alias' $cmdlet.Definition)[0]
             }

             # expand the parameter sets and emit the matching elements
             foreach ($n in $cmdlet.ParameterSets | Select-Object -expand parameters)
             {
                 $n = $n.name
                 if ($n -like $pat) { '-'   $n }
             }
             break;
         }

         default {
             $varNameStar = $lastWord   '*';

             foreach ($n in @(Get-Childitem $varNameStar))
             {
                 $name = PathRelativeTo ($n) ($PWD);

                 if ($n.PSIsContainer)
                 {
                     EscapePath ($name   '\') ($lastWord);
                 }
                 else
                 {
                     EscapePath ($name) ($lastWord);
                 }
             }

             if (!$varNameStar.Contains('\'))
             {
                foreach ($n in @(Get-Command $varNameStar))
                {
                    if ($n.CommandType.ToString().Equals('Application'))
                    {
                       foreach ($ext in @((cat Env:PathExt).Split(';')))
                       {
                          if ($n.Path.ToString().ToLower().EndsWith(($ext).ToString().ToLower()))
                          {
                              EscapePath($n.Path) ($lastWord);
                          }
                       }
                    }
                    else
                    {
                        EscapePath($n.Name) ($lastWord);
                    }
                }

                foreach ($n in @(Get-psdrive $varNameStar))
                {
                    EscapePath($n.name   ":") ($lastWord);
                }
             }

             foreach ($n in @(Get-History))
             {
                 if ($n.CommandLine.StartsWith($line) -and $n.CommandLine -ne $line)
                 {
                     $lastWord   $n.CommandLine.Substring($line.Length);
                 }
             }

             # Add the original string to the end of the expansion list.
             $lastWord;

             break;
         }
    }
}

PermalinkCommentscli technical tabexpansion powershell

Paint.NET - Free Software for Digital Photo Editing

2008 May 5, 11:45Free OpenSource C# paint program replacement with many more features than paint.exe =)PermalinkCommentswindows photo art microsoft csharp .net opensource development free paint

Create a Windows Clipboard Monitor in C# using SetClipboardViewer API - Rad Software

2008 Apr 21, 2:58"This example shows you how to use the Win32 API function SetClipboardViewer to create a Clipboard Viewer application" and the example is in C# and VB.Net.PermalinkComments.net csharp clipboard programming windows setclipboardviewer dllimport

Encoding methods in C#

2008 Apr 12, 10:38

For Encode-O-Matic, my encoding tool written in C#, I had to figure out the appropriate DllImport declarations to use IDN Win32 functions which was a pain. To spare others that pain here's the two files CharacterSetEncoding.cs and NationalLanguageSupportUtilities.cs that declare the DllImports for IdnToUnicode, IdnToAscii, NormalizeString, MultiByteToWideChar, and WideCharToMultiByte.

PermalinkCommentsencodeomatic boring csharp widechartomultibyte idn tool dllimport

Old Miscellaneous Thoughts

2007 Dec 26, 5:45PermalinkCommentspopfly apple personal history-channel indiana-jones pipes mac technical microsoft mashup yahoo nontechnical

C# Graph Layout Library

2007 Feb 22, 7:23A C# graph layout library for free from Microsoft Research.PermalinkComments.net free graph microsoft research visualization csharp library glee

Introduction - VSA Scripting in .NET - Developer Fusion, the UK developer community - VB, ASP, C#, .NET, PHP and XML tutorials & source code

2006 Aug 17, 10:01PermalinkCommentsscript .net csharp javascript vbscript programming

Lutz Roeder's Programming.NET C# VB CLR WinFX

2005 Dec 5, 6:04PermalinkCommentsfree software csharp dotnet development decompiler tools windows reflector
Older Entries Creative Commons License Some rights reserved.