コード例 #1
0
        public static bool DesktopExists(string desktopName)
        {
            var handle = WinApi.OpenDesktop(desktopName, 0, false, 0);

            WinApi.CloseDesktop(handle);
            return(handle != IntPtr.Zero);
        }
コード例 #2
0
        public static void CloseDesktopWindows(string desktopName)
        {
            var handle = WinApi.OpenDesktop(desktopName, 0, false, 0);

            if (handle == IntPtr.Zero)
            {
                WriteLine($"INFO: Desktop '{desktopName}' not found.");
                return;
            }
            var windows = new List <IntPtr>();

            WinApi.EnumDesktopWindows(handle, (hwnd, _) =>
            {
                windows.Add(hwnd);
                return(true);
            }, IntPtr.Zero);

            WriteLine($"INFO: Top level windows in the headless desktop: {windows.Count}");
            if (windows.Count > 0)
            {
                foreach (var hWindow in windows)
                {
                    var windowHandle = new HandleRef(null, hWindow);
                    WriteLine($"INFO: Quitting the '{windows.Count}' top level window.'");
                    WinApi.PostMessage(windowHandle, WinApi.WM_ENDSESSION, IntPtr.Zero,
                                       (IntPtr)1 /* ENDSESSION_CLOSEAPP */);
                    WinApi.PostMessage(windowHandle, WinApi.WM_QUIT, IntPtr.Zero, IntPtr.Zero);
                }

                Thread.Sleep(2000);
                windows.Clear();
                WinApi.EnumDesktopWindows(handle, (hwnd, _) =>
                {
                    windows.Add(hwnd);
                    return(true);
                }, IntPtr.Zero);
                WriteLine($"INFO: Top level windows after sending quit message: {windows.Count}");
            }

            WinApi.CloseDesktop(handle);
        }