11using System ;
2+ using System . Runtime . InteropServices ;
23using System . Threading . Tasks ;
34using System . Windows ;
45using System . Windows . Interop ;
@@ -10,6 +11,14 @@ namespace ScreenSleep
1011 /// </summary>
1112 public partial class MainWindow : Window
1213 {
14+ [ DllImport ( "user32.dll" ) ]
15+ static extern IntPtr SetParent ( IntPtr hwnd , IntPtr hwndNewParent ) ;
16+
17+ // https://stackoverflow.com/questions/1399037/loading-a-wpf-window-without-showing-it
18+ private const int HWND_MESSAGE = - 3 ;
19+ private IntPtr hwnd ;
20+ private IntPtr oldParent ;
21+
1322 public WindowInteropHelper Helper ;
1423
1524 public MainWindow ( )
@@ -21,9 +30,17 @@ private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
2130 Settings . SetupStartup ( ) ;
2231
2332 Helper = new WindowInteropHelper ( this ) ;
33+ Helper . EnsureHandle ( ) ;
34+
35+ if ( PresentationSource . FromVisual ( this ) is HwndSource source )
36+ {
37+ source . AddHook ( WndProc ) ;
2438
25- var source = PresentationSource . FromVisual ( this ) as HwndSource ;
26- source . AddHook ( WndProc ) ;
39+ hwnd = source . Handle ;
40+ oldParent = SetParent ( hwnd , ( IntPtr ) HWND_MESSAGE ) ;
41+ Visibility = Visibility . Hidden ;
42+ ShowActivated = false ;
43+ }
2744
2845 Settings . SetupSleepShortcut ( Helper ) ;
2946 }
@@ -41,7 +58,10 @@ private void Settings_OnClick(object sender, RoutedEventArgs e)
4158
4259 private void TurnOff_OnClick ( object sender , RoutedEventArgs e )
4360 {
44- if ( MyNotifyIcon . ContextMenu != null ) MyNotifyIcon . ContextMenu . IsOpen = false ;
61+ this . Dispatcher . Invoke ( ( ) =>
62+ {
63+ if ( MyNotifyIcon . ContextMenu != null ) MyNotifyIcon . ContextMenu . IsOpen = false ;
64+ } ) ;
4565
4666 Screen . SetScreenState ( ScreenState . Off ) ;
4767 }
0 commit comments