diff --git a/WinPowerHelper.Wpf/App.xaml b/WinPowerHelper.Wpf/App.xaml index 7981f7e..084f8e9 100644 --- a/WinPowerHelper.Wpf/App.xaml +++ b/WinPowerHelper.Wpf/App.xaml @@ -2,8 +2,8 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:viewmodels="clr-namespace:WinPowerHelper.Wpf.ViewModels" - StartupUri="MainWindow.xaml" - xmlns:system="clr-namespace:System;assembly=System.Runtime"> + xmlns:system="clr-namespace:System;assembly=System.Runtime" + StartupUri="MainWindow.xaml"> diff --git a/WinPowerHelper.Wpf/App.xaml.cs b/WinPowerHelper.Wpf/App.xaml.cs index 6d383fe..99e5925 100644 --- a/WinPowerHelper.Wpf/App.xaml.cs +++ b/WinPowerHelper.Wpf/App.xaml.cs @@ -1,11 +1,32 @@ namespace WinPowerHelper { + using System; + using System.Threading; using System.Windows; + using WinPowerHelper.Wpf.Interaction; /// /// Interaction logic for App.xaml /// public partial class App : Application { + public App() + { + Startup += (e, args) => + { + _mutex = new Mutex(true, "WinPowerHelper", out bool isNew); + if (!isNew) + { + NativeMethods.PostMessage( + (IntPtr)NativeMethods.HWND_BROADCAST, + NativeMethods.WM_SHOWME, + IntPtr.Zero, + IntPtr.Zero); + Environment.Exit(0); + } + }; + } + + private Mutex _mutex; } } diff --git a/WinPowerHelper.Wpf/Interaction/NativeMethods.cs b/WinPowerHelper.Wpf/Interaction/NativeMethods.cs new file mode 100644 index 0000000..798c4bc --- /dev/null +++ b/WinPowerHelper.Wpf/Interaction/NativeMethods.cs @@ -0,0 +1,15 @@ +namespace WinPowerHelper.Wpf.Interaction +{ + using System; + using System.Runtime.InteropServices; + + internal class NativeMethods + { + public const int HWND_BROADCAST = 0xffff; + public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME"); + [DllImport("user32")] + public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); + [DllImport("user32", CharSet = CharSet.Unicode)] + public static extern int RegisterWindowMessage(string message); + } +} diff --git a/WinPowerHelper.Wpf/MainWindow.xaml.cs b/WinPowerHelper.Wpf/MainWindow.xaml.cs index 817bcd9..961e550 100644 --- a/WinPowerHelper.Wpf/MainWindow.xaml.cs +++ b/WinPowerHelper.Wpf/MainWindow.xaml.cs @@ -1,6 +1,9 @@ namespace WinPowerHelper { + using System; using System.Windows; + using System.Windows.Interop; + using WinPowerHelper.Wpf.Interaction; /// /// Interaction logic for MainWindow.xaml @@ -11,5 +14,19 @@ public MainWindow() { InitializeComponent(); } + + protected override void OnSourceInitialized(EventArgs e) + { + base.OnSourceInitialized(e); + var source = PresentationSource.FromVisual(this) as HwndSource; + source.AddHook(WndProc); + } + + private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled) + { + if (msg == NativeMethods.WM_SHOWME) + Activate(); + return IntPtr.Zero; + } } }