public static void HandleSecondInstanceMessages(DpiAwareWindow window, Action<IEnumerable<string>> handler) {
HwndSource hwnd = null;
HwndSourceHook hook = (IntPtr handle, int message, IntPtr wParam, IntPtr lParam, ref bool handled) => {
if (message == SecondInstanceMessage) {
try {
handler(ReceiveSomeData());
window.BringToFront();
} catch (Exception e) {
Logging.Warning("Can’t handle message: " + e);
}
}
return IntPtr.Zero;
};
RoutedEventHandler[] handlers = { null, null };
// loaded
handlers[0] = (sender, args) => {
window.Loaded -= handlers[0];
try {
hwnd = HwndSource.FromHwnd(new WindowInteropHelper(window).Handle);
if (hwnd == null) {
Logging.Warning("Can’t add one-instance hook: HwndSource is null");
return;
}
hwnd.AddHook(hook);
window.Unloaded += handlers[1];
} catch (Exception e) {
Logging.Warning("Can’t add one-instance hook: " + e);
hook = null;
}
};
// unloaded
handlers[1] = (sender, args) => {
window.Unloaded -= handlers[1];
try {
hwnd.RemoveHook(hook);
} catch (Exception e) {
Logging.Warning("Can’t remove one-instance hook: " + e);
hook = null;
}
};
if (!window.IsLoaded) {
window.Loaded += handlers[0];
} else {
handlers[0](null, null);
}
}
}