Skip to content

Commit

Permalink
Switch Win32 event to .Net Semaphore (#263)
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeHillberg committed Oct 27, 2022
1 parent 4501c21 commit 78bb26c
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows10.0.19041.0</TargetFramework>
<TargetFramework>net6.0-windows10.0.19041.0</TargetFramework>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<RootNamespace>CsWinUiDesktopInstancing</RootNamespace>
<ApplicationManifest>app.manifest</ApplicationManifest>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,37 +202,20 @@ private static bool DecideRedirection()
return isRedirect;
}

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr CreateEvent(
IntPtr lpEventAttributes, bool bManualReset,
bool bInitialState, string lpName);

[DllImport("kernel32.dll")]
private static extern bool SetEvent(IntPtr hEvent);

[DllImport("ole32.dll")]
private static extern uint CoWaitForMultipleObjects(
uint dwFlags, uint dwMilliseconds, ulong nHandles,
IntPtr[] pHandles, out uint dwIndex);

private static IntPtr redirectEventHandle = IntPtr.Zero;

// Do the redirection on another thread, and use a non-blocking
// wait method to wait for the redirection to complete.
public static void RedirectActivationTo(
AppActivationArguments args, AppInstance keyInstance)
{
redirectEventHandle = CreateEvent(IntPtr.Zero, true, false, null);
var redirectSemaphore = new Semaphore(0, 1);
Task.Run(() =>
{
keyInstance.RedirectActivationToAsync(args).AsTask().Wait();
SetEvent(redirectEventHandle);
redirectSemaphore.Release();
});
uint CWMO_DEFAULT = 0;
uint INFINITE = 0xFFFFFFFF;
_ = CoWaitForMultipleObjects(
CWMO_DEFAULT, INFINITE, 1,
new IntPtr[] { redirectEventHandle }, out uint handleIndex);
redirectSemaphore.WaitOne();
}

#endregion
Expand Down

0 comments on commit 78bb26c

Please sign in to comment.