win32 - Dave's Blog

Search
My timeline on Mastodon

Changing the User Agent string in UWP WebView

2018 Oct 23, 9:32

There's no perfect way to change the user agent string for the UWP WebView (x-ms-webview in HTML, Windows.UI.Xaml.Controls.WebView in XAML, and Windows.Web.UI.Interop.WebViewControl in Win32) but there are two imperfect methods folks end up using.

The first is to call UrlMkSetSessionOption. This is an old public API that allows you to configure various arcane options including one that is the default user agent string for requests running through urlmon. This API is allowed by the Microsoft Store for UWP apps. The change it applies is process wide which has two potential drawbacks. If you want to be able to have different UA strings set for different requests from a WebView that's not really possible with this solution. The other drawback is if you're using out of process WebView, you need to ensure you're calling into UrlMkSetSessionOption in the WebView's process. You'll need to write third party WinRT that calls UrlMkSetSessionOption, create the out of proc WebView, navigate it to some trusted local page, use AddWebAllowedObject or provide that URI WinRT access, and call into your third party WinRT. You'll need to do that for any new WebView process you create.

The second less generally applicable solution is to use NavigateWithHttpRequestMessage and set the User-Agent HTTP header. In this case you get to control the scope of the user agent string changes but has the limitations that not all sub resource downloads will use this user agent string and for navigations you don't initiate you have to manually intercept and re-request being careful to transfer over all POST body state and HTTP headers correctly. That last part is not actually possible for iframes.

PermalinkCommentsuser-agent uwp webview

GoBack/GoForward in Win10 UWP WebView

2018 Oct 23, 9:18

The GoBack and GoForward methods on the UWP WebView (x-ms-webview in HTML, Windows.UI.Xaml.Controls.WebView in XAML, and Windows.Web.UI.Interop.WebViewControl in Win32) act the same as the Back and Forward buttons in the Edge browser. They don't necessarily change the top level document of the WebView. If inside the webview an iframe navigates then that navigation will be recorded in the forward/back history and the GoBack / GoForward call may result in navigating that iframe. This makes sense as an end user using the Edge browser since if I click a link to navigate one place and then hit Back I expect to sort of undo that most recent navigation regardless of if that navigation happened in an iframe or the top level document.

If that doesn't make sense for your application and you want to navigate forward or back ignoring iframe navigates, unfortunately there's no perfect workaround.

One workaround could be to try calling GoBack and then checking if a FrameNavigationStarting event fires or a NavigationStarting event fires. If a frame navigates then try calling GoBack again. There could be async races in this case since other navigates could come in and send you the wrong signal and interrupt your multi step GoBack operation.

You could also try keeping track of all top level document navigations and manually navigate back to the URIs you care about. However, GoBack and GoForward also restore some amount of user state (form fills etc) in addition to navigating. Manually calling navigate will not give this same behavior.

PermalinkCommentsuri uwp webview

Windows.Web.UI.Interop.WebViewControl localhost access

2018 Jul 25, 5:34

If you're developing with the new Windows.Web.UI.Interop.WebViewControl you may have noticed you cannot navigate to localhost HTTP servers. This is because the WebViewControl's WebView process is a UWP process. All UWP processes by default cannot use the loopback adapter as a security precaution. For development purposes you can allow localhost access using the checknetisolation command line tool on the WebViewControl's package just as you can for any other UWP app. The command should be the following:

checknetisolation loopbackexempt -a -n=Microsoft.Win32WebViewHost_cw5n1h2txyewy

As a warning checknetisolation is not good on errors. If you attempt to add a package but get its package family name wrong, checknetisolation just says OK:

C:\Users\davris>checknetisolation LoopbackExempt -a -n=Microsoft.BingWeather_4.21.2492.0_x86__8wekyb3d8bbwe
OK.
And if you then list the result of the add with the bad name you'll see the following:
[1] -----------------------------------------------------------------
Name: AppContainer NOT FOUND
SID: S-1-15-...

There's also a UI tool for modifying loopback exemption for packages available on GitHub and also one available with Fiddler.

As an additional note, I mentioned above you can try this for development. Do not do this in shipping products as this turns off the security protection for any consumer of the WebViewControl.

PermalinkCommentschecknetisolation loopback security uwp webview win32webview

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

Debugging LoadLibrary Failures - Junfeng Zhang's Windows Programming Notes - Site Home - MSDN Blogs

2014 Feb 25, 2:22

How to turn on debug logging for LoadLibrary to diagnose failures. For example, see where in the dependency graph of a DLL LoadLibrary ran into issues.

PermalinkCommentstechnical win32 windows debugging loadlibrary

Thread Local Storage, part 1: Overview « Nynaeve

2011 Aug 6, 1:53Description of the inner workings of both of Window's TLS options, the Win32 APIs like TlsAlloc as well as __declspec(thread). I didn't know that the max number of TLS indices is now 1088.PermalinkCommentsblog programming development windows debug tls thread-local-storage

Command line for finding missing URLACTIONs

2011 May 28, 11:00

I wanted to ensure that my switch statement in my implementation of IInternetSecurityManager::ProcessURLAction had a case for every possible documented URLACTION. I wrote the following short command line sequence to see the list of all URLACTIONs in the SDK header file not found in my source file:

grep URLACTION urlmon.idl | sed 's/.*\(URLACTION[a-zA-Z0-9_]*\).*/\1/g;' | sort | uniq > allURLACTIONs.txt
grep URLACTION MySecurityManager.cpp | sed 's/.*\(URLACTION[a-zA-Z0-9_]*\).*/\1/g;' | sort | uniq > myURLACTIONs.txt
comm -23 allURLACTIONs.txt myURLACTIONs.txt
I'm not a sed expert so I had to read the sed documentation, and I heard about comm from Kris Kowal's blog which happilly was in the Win32 GNU tools pack I already run.

But in my effort to learn and use PowerShell I found the following similar command line:

diff 
(more urlmon.idl | %{ if ($_ -cmatch "URLACTION[a-zA-Z0-9_]*") { $matches[0] } } | sort -uniq)
(more MySecurityManager.cpp | %{ if ($_ -cmatch "URLACTION[a-zA-Z0-9_]*") { $matches[0] } } | sort -uniq)
In the PowerShell version I can skip the temporary files which is nice. 'diff' is mapped to 'compare-object' which seems similar to comm but with no parameters to filter out the different streams (although this could be done more verbosely with the ?{ } filter syntax). In PowerShell uniq functionality is built into sort. The builtin -cmatch operator (c is for case sensitive) to do regexp is nice plus the side effect of generating the $matches variable with the regexp results.
PermalinkCommentspowershell tool cli technical command line

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

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

IEBlog : URI Comparison Functions

2007 Oct 24, 1:19My blog post on unmanaged Win32 URI comparison functions.PermalinkCommentsie blog me uri microsoft win32 windows

IEBlog: URI Comparison Functions

2007 Oct 24, 6:20I have a new post on the IE Blog on the topic of Win32 URI Comparison Functions.
I've blogged there previously on the topics of IPv6 URIs in IE7, International Mailto URIs in IE7, File URIs in Windows, and CreateURLMoniker Considered Harmful. Hooray for URIs!PermalinkCommentsmicrosoft technical blog url win32 ie windows uri

Native Win32 ports of some GNU utilities

2007 Aug 9, 1:33Win32 versions of many common Unix commands.PermalinkCommentsunix linux tool tools download windows sourceforge shell software free

Which which - Batch File Hackiness

2007 Aug 9, 5:41To satisfy my hands which have already learned to type *nix commands I like to install Win32 versions of common GNU utilities. Unfortunately, the which command is a rather literal port and requires you to enter the entire name of the command for which you're looking. That is 'which which' won't find itself but 'which which.exe' will. This makes this almost useless for me so I thought to write my own as a batch file. I had learned about a few goodies available in cmd.exe that I thought would make this an easy task. It turned out to be more difficult than I thought.

for /F "usebackq tokens=*" %%a in ( `"echo %PATH:;=& echo %"` ) do (
    for /F "usebackq tokens=*" %%b in ( `"echo %PATHEXT:;=& echo %"` ) do (
        if exist "%%a"\%1%%b (
            for  %%c in ( "%%a"\%1%%b ) do (
                echo %%~fc
            )
        )
    )
)
The environment variables PATH and PATHEXT hold the list of paths to search through to find commands, and the extensions of files that should be run as commands respectively. The 'for /F "usebackq tokens=*" %%a in (...) do (...)' runs the 'do' portion with %%a sequentially taking on the value of every line in the 'in' portion. That's nice, but PATH and PATHEXT don't have their elements on different lines and I don't know of a way to escape a newline character to appear in a batch file. In order to get the PATH and PATHEXT's elements onto different lines I used the %ENV:a=b% syntax which replaces occurrences of a with b in the value of ENV. I replaced the ';' delimiter with the text '& echo ' which means %PATHEXT:;=& echo% evaluates to something like "echo .COM& echo .EXE& echo .BAT& ...". I have to put the whole expression in double quotes in order to escape the '&' for appearing in the batch file. The usebackq and the backwards quotes means that the backquoted string should be replaced with the output of the execution of its content. So in that fashion I'm able to get each element of the env. variable onto new lines. The rest is pretty straight forward.

Also, it supports wildcards:
C:\Users\davris>which.cmd *hi*
C:\Windows\System32\GRAPHICS.COM
C:\Windows\System32\SearchIndexer.exe
D:\bin\which.exe
D:\bin\which.cmd
PermalinkCommentswhich cmd technical batch for
Older Entries Creative Commons License Some rights reserved.