public void OnWndProc(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam,
                              bool restorePlacement, bool activate)
        {
            if (msg != SingleInstanceMessage)
            {
                return;
            }

            if (restorePlacement)
            {
                WindowPlacement placement = WindowPlacement.GetPlacement(hwnd, false);

                if (placement.IsValid && placement.IsMinimized)
                {
                    placement.ShowCmd = WindowNative.SwShowNormal;

                    placement.SetPlacement(hwnd);
                }
            }

            if (!activate)
            {
                return;
            }

            WindowNative.SetForegroundWindow(hwnd);
            WindowUtils.ActivateWindow(WindowUtils.GetModalWindow(hwnd));
        }
예제 #2
0
        public static AppWindow GetAppWindowForCurrentWindow(this Window window)
        {
            var hWnd  = WindowNative.GetWindowHandle(window);
            var winId = Win32Interop.GetWindowIdFromWindow(hWnd);

            return(AppWindow.GetFromWindowId(winId));
        }
예제 #3
0
        private AppWindow GetAppWindowForCurrentWindow()
        {
            IntPtr   hWnd  = WindowNative.GetWindowHandle(this);
            WindowId wndId = Win32Interop.GetWindowIdFromWindow(hWnd);

            return(AppWindow.GetFromWindowId(wndId));
        }
예제 #4
0
        public static void RegisterHotKey(CaptureMode mode)
        {
            if (Handle == IntPtr.Zero)
            {
                return;
            }
            if (!HotKeys.ContainsKey(mode))
            {
                return;
            }

            var hotKey = HotKeys[mode];

            if (hotKey == null)
            {
                return;
            }

            if (hotKey.IsRegistered)
            {
                UnregisterHotKey(mode);
            }

            if (hotKey.Modifiers == WindowNative.KeyModifiers.None && hotKey.Key == Keys.None)
            {
                return;
            }

            if (WindowNative.RegisterHotKey(Handle, (int)mode, hotKey.Modifiers, hotKey.Key))
            {
                hotKey.IsRegistered = true;
            }
        }
예제 #5
0
 public static void UpdateWallpaper()
 {
     WindowNative.SystemParametersInfo(SPI_SETDESKWALLPAPER,
                                       0,
                                       null,
                                       SPIF_SENDWININICHANGE);
 }
예제 #6
0
 public static void Init()
 {
     SystemNative.Load();
     WindowNative.Load();
     GraphicsNative.Load();
     AudioNative.Load();
 }
        public async Task <bool> WaitMutex(bool force, IntPtr wParam, IntPtr lParam)
        {
            bool exist = !WaitMutexInternal(force);

            if (exist)
            {
                string[] originalArgs = Environment.GetCommandLineArgs();
                string[] args         = new string[originalArgs.Length - 1];

                if (args.Length > 0)
                {
                    args = originalArgs.Skip(1).ToArray();
                }

                if (args.Length > 0)
                {
                    await SendMessageStringUtf8("SendArgs",
                                                string.Join(" || ", args))
                    .ConfigureAwait(true);
                }
                else
                {
                    _ = WindowNative.PostMessage((IntPtr)WindowNative.HwndBroadcast,
                                                 SingleInstanceMessage, wParam, lParam);
                }
            }
            else
            {
                InstanceBus = new TinyMessageBus($"Bus_{UniqueName}");
                InstanceBus.MessageReceived += InstanceBus_MessageReceived;
            }

            return(!exist);
        }
예제 #8
0
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
            await ApplicationDataMigration.Migrate();

            await DatabaseManager.Instance.InitializeDb();

            await SettingsViewModel.Instance.Load();

            await SearchResultsViewModel.Instance.Load();

            if (!Resources.ContainsKey("settings"))
            {
                Resources.Add("settings", Settings.Instance);
            }

            string[] args            = Environment.GetCommandLineArgs();
            string   launchArguments = args.Length >= 2 ? args[1] : null;

            mainWindow = new MainWindow(launchArguments);

            IntPtr    hWnd      = WindowNative.GetWindowHandle(mainWindow);
            WindowId  windowId  = Win32Interop.GetWindowIdFromWindow(hWnd);
            AppWindow appWindow = AppWindow.GetFromWindowId(windowId);

            mainWindow.Activate();

            appWindow.Closing += AppWindow_Closing;
        }
예제 #9
0
 public static void ActivateWindow(
     IntPtr hwnd)
 {
     if (hwnd != IntPtr.Zero)
     {
         WindowNative.SetActiveWindow(hwnd);
     }
 }
예제 #10
0
        public static void AppendToWallpaperArea(IntPtr handle)
        {
            if (HandleUtil.NeedSeparation)
            {
                HandleUtil.SpawnWorker();
            }

            WindowNative.SetParent(handle, HandleUtil.WallpaperArea);
        }
예제 #11
0
 private float CalcScale()
 {
     using (var g = Graphics.FromHwnd(IntPtr.Zero))
     {
         IntPtr desktop              = g.GetHdc();
         int    logicalScreenHeight  = WindowNative.GetDeviceCaps(desktop, (int)WindowNative.DeviceCap.VERTRES);
         int    physicalScreenHeight = WindowNative.GetDeviceCaps(desktop, (int)WindowNative.DeviceCap.DESKTOPVERTRES);
         return((float)physicalScreenHeight / logicalScreenHeight);
     }
 }
예제 #12
0
        public static IntPtr GetModalWindow(
            IntPtr owner)
        {
            var window = new ModalWindow();

            WindowNative.EnumThreadWindows(
                WindowNative.GetCurrentThreadId(),
                window.EnumChildren, owner);

            return(window.MaxOwnershipHandle);
        }
예제 #13
0
        public static IntPtr GetWindowHandle(this UI.Xaml.Window platformWindow)
        {
            var hwnd = WindowNative.GetWindowHandle(platformWindow);

            if (hwnd == IntPtr.Zero)
            {
                throw new NullReferenceException("The Window Handle is null.");
            }

            return(hwnd);
        }
예제 #14
0
        private Image CaptureWindow(CaptureMode mode)
        {
            Image     img     = null;
            IntPtr    handle  = IntPtr.Zero;
            Rectangle monitor = Rectangle.Empty;

            switch (mode)
            {
            case CaptureMode.FullScreen:
                handle = WindowNative.GetDesktopWindow();
                if (CaptureSetting.FullScreenMode == FullScreenMode.MainMonitor)
                {
                    monitor = Screen.PrimaryScreen.Bounds;
                }
                else if (CaptureSetting.FullScreenMode == FullScreenMode.ActiveMonitor)
                {
                    monitor = Screen.GetBounds(Cursor.Position);
                }
                else if (CaptureSetting.FullScreenMode == FullScreenMode.AllMonitor)
                {
                    monitor = SystemInformation.VirtualScreen;
                }
                img = CaptureWindow(handle, monitor.X, monitor.Y, monitor.Width, monitor.Height);
                break;

            case CaptureMode.ActiveProcess:
                handle = WindowNative.GetForegroundWindow();
                img    = CaptureWindow(handle, 0, 0, 0, 0);
                break;

            case CaptureMode.Region:
                handle  = WindowNative.GetDesktopWindow();
                monitor = SystemInformation.VirtualScreen;

                using (var tmp = CaptureWindow(handle, monitor.X, monitor.Y, monitor.Width, monitor.Height))
                    using (var dialog = new CaptureBackgroundDialog(tmp))
                    {
                        dialog.TopMost = true;
                        dialog.BringToFront();
                        if (dialog.ShowDialog() != DialogResult.OK)
                        {
                            return(null);
                        }

                        img = dialog.Image;
                    }
                break;

            default: return(null);
            }
            return(img);
        }
        public SingleInstanceApp(string uniqueName)
        {
            if (uniqueName == null)
            {
                throw new ArgumentNullException(nameof(uniqueName));
            }

            UniqueName = uniqueName;

            LocalBus = new TinyMessageBus($"Bus_{uniqueName}");

            Mutex = new Mutex(true, uniqueName);
            SingleInstanceMessage = WindowNative.RegisterWindowMessage($"WM_{uniqueName}");
        }
예제 #16
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            Window = new MainWindow();

            WindowId id = Win32Interop.GetWindowIdFromWindow(WindowNative.GetWindowHandle(Window));

            AppWindow = AppWindow.GetFromWindowId(id);

            AppWindow.TitleBar.ExtendsContentIntoTitleBar = true;

            await Task.Run(AppInitiating);

            Window.Navigate(typeof(Pages.CommonPage));

            Window.Activate();
        }
예제 #17
0
        private void SetTitleBarColorsAndIcon()
        {
            IntPtr    hWnd      = WindowNative.GetWindowHandle(this);
            WindowId  windowId  = Win32Interop.GetWindowIdFromWindow(hWnd);
            AppWindow appWindow = AppWindow.GetFromWindowId(windowId);

            // Title bar customization is not supported on Windows 10
            if (AppWindowTitleBar.IsCustomizationSupported())
            {
                AppWindowTitleBar titleBar = appWindow.TitleBar;

                ResourceDictionary dictionary = null;

                switch (Settings.Instance.AppTheme)
                {
                case ElementTheme.Default:
                    dictionary = Application.Current.Resources;
                    break;

                case ElementTheme.Light:
                    dictionary = (ResourceDictionary)Application.Current.Resources.ThemeDictionaries["Light"];
                    break;

                case ElementTheme.Dark:
                    dictionary = (ResourceDictionary)Application.Current.Resources.ThemeDictionaries["Dark"];
                    break;
                }

                titleBar.BackgroundColor               = (Color?)dictionary["TitleBarBackgroundColor"];
                titleBar.ForegroundColor               = (Color?)dictionary["TitleBarForegroundColor"];
                titleBar.InactiveBackgroundColor       = (Color?)dictionary["TitleBarInactiveBackgroundColor"];
                titleBar.InactiveForegroundColor       = (Color?)dictionary["TitleBarInactiveForegroundColor"];
                titleBar.ButtonBackgroundColor         = (Color?)dictionary["TitleBarButtonBackgroundColor"];
                titleBar.ButtonHoverBackgroundColor    = (Color?)dictionary["TitleBarButtonHoverBackgroundColor"];
                titleBar.ButtonForegroundColor         = (Color?)dictionary["TitleBarButtonForegroundColor"];
                titleBar.ButtonHoverForegroundColor    = (Color?)dictionary["TitleBarButtonHoverForegroundColor"];
                titleBar.ButtonPressedBackgroundColor  = (Color?)dictionary["TitleBarButtonPressedBackgroundColor"];
                titleBar.ButtonPressedForegroundColor  = (Color?)dictionary["TitleBarButtonPressedForegroundColor"];
                titleBar.ButtonInactiveBackgroundColor = (Color?)dictionary["TitleBarButtonInactiveBackgroundColor"];
                titleBar.ButtonInactiveForegroundColor = (Color?)dictionary["TitleBarButtonInactiveForegroundColor"];
            }

            string applicationRoot = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            appWindow.SetIcon(Path.Combine(applicationRoot, @"Assets\Logo.ico"));
        }
예제 #18
0
        private double GetScaleAdjustment()
        {
            IntPtr      hWnd        = WindowNative.GetWindowHandle(this);
            WindowId    wndId       = Win32Interop.GetWindowIdFromWindow(hWnd);
            DisplayArea displayArea = DisplayArea.GetFromWindowId(wndId, DisplayAreaFallback.Primary);
            IntPtr      hMonitor    = Win32Interop.GetMonitorFromDisplayId(displayArea.DisplayId);

            // Get DPI.
            int result = GetDpiForMonitor(hMonitor, Monitor_DPI_Type.MDT_Default, out uint dpiX, out uint _);

            if (result != 0)
            {
                throw new Exception("Could not get DPI for monitor.");
            }

            uint scaleFactorPercent = (uint)(((long)dpiX * 100 + (96 >> 1)) / 96);

            return(scaleFactorPercent / 100.0);
        }
        public void OnWndProc(System.Windows.Window window, IntPtr hwnd, uint msg,
                              IntPtr wParam, IntPtr lParam, bool restorePlacement, bool activate)
        {
            if (!(window is INativeRestorableWindow restorableWindow))
            {
                OnWndProc(hwnd, msg, wParam, lParam, restorePlacement, activate);

                return;
            }

            if (msg != SingleInstanceMessage)
            {
                return;
            }

            if (restorePlacement)
            {
                WindowPlacement placement = WindowPlacement.GetPlacement(hwnd, false);

                if (placement.IsValid && placement.IsMinimized)
                {
                    placement.Flags |= WindowNative.WpfAsyncWindowPlacement;

                    placement.ShowCmd = restorableWindow.DuringRestoreToMaximized
                        ? WindowNative.SwShowMaximized
                        : WindowNative.SwShowNormal;

                    placement.SetPlacement(hwnd);
                }
            }

            if (!activate)
            {
                return;
            }

            WindowNative.SetForegroundWindow(hwnd);
            WindowUtils.ActivateWindow(WindowUtils.GetModalWindow(hwnd));
        }
예제 #20
0
        public static void UnregisterHotKey(CaptureMode mode)
        {
            if (Handle == IntPtr.Zero)
            {
                return;
            }
            if (!HotKeys.ContainsKey(mode))
            {
                return;
            }

            var hotKey = HotKeys[mode];

            if (hotKey == null)
            {
                return;
            }

            if (WindowNative.UnregisterHotKey(Handle, (int)mode))
            {
                hotKey.IsRegistered = false;
            }
        }
예제 #21
0
        public static bool IsOwned(
            IntPtr owner, IntPtr hwnd,
            ref int level)
        {
            while (true)
            {
                var ownerWindow = WindowNative
                                  .GetWindow(hwnd, ModalWindow.GwOwner);

                if (ownerWindow == IntPtr.Zero)
                {
                    return(false);
                }

                if (ownerWindow == owner)
                {
                    return(true);
                }

                ++level;

                hwnd = ownerWindow;
            }
        }
예제 #22
0
        public static void RemoveFromWallpaperArea(IntPtr handle)
        {
            WindowNative.SetParent(handle, IntPtr.Zero);

            UpdateWallpaper();
        }
예제 #23
0
 public void Update()
 {
     WindowNative.SendMessage(Handle, 15U, (IntPtr)0, (IntPtr)0);
 }
예제 #24
0
        private Image CaptureWindow(IntPtr handle, int x, int y, int width, int height)
        {
            Image  img      = null;
            IntPtr srcDC    = IntPtr.Zero;
            IntPtr memoryDC = IntPtr.Zero;
            IntPtr bitmap   = IntPtr.Zero;

            try
            {
                // 해당 Handle의 크기 취득
                if (width == 0 || height == 0)
                {
                    var windowRect = new WindowNative.Rect();
                    var clientRect = new WindowNative.Rect();
                    WindowNative.GetWindowRect(handle, ref windowRect);
                    WindowNative.GetClientRect(handle, ref clientRect);
                    if (x == 0)
                    {
                        x = windowRect.Left;
                    }
                    if (y == 0)
                    {
                        y = windowRect.Top;
                    }
                    if (width == 0)
                    {
                        width = clientRect.Width;
                    }
                    if (height == 0)
                    {
                        height = windowRect.Height;
                    }

                    // Border 사이즈 제외
                    int diff = windowRect.Width - clientRect.Width;
                    if (diff > 0)
                    {
                        int borderSize = diff / 2;
                        x      += borderSize;
                        y      += borderSize;
                        height -= borderSize * 2;
                    }
                }

                // 해상도 스케일에 의한 크기 변경
                float scale = CalcScale();
                if (scale > 1)
                {
                    width  = (int)(width * scale);
                    height = (int)(height * scale);
                }

                handle   = WindowNative.GetDesktopWindow();
                srcDC    = WindowNative.GetWindowDC(handle);
                memoryDC = WindowNative.CreateCompatibleDC(srcDC);
                bitmap   = WindowNative.CreateCompatibleBitmap(srcDC, width, height);

                IntPtr oldBitmap = WindowNative.SelectObject(memoryDC, bitmap);
                WindowNative.BitBlt(memoryDC, 0, 0, width, height, srcDC, x, y, WindowNative.SRCCOPY | WindowNative.CAPTUREBLT);
                WindowNative.SelectObject(memoryDC, oldBitmap);

                img = Image.FromHbitmap(bitmap);
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
            finally
            {
                WindowNative.DeleteObject(bitmap);
                WindowNative.DeleteDC(memoryDC);
                WindowNative.ReleaseDC(handle, srcDC);
            }

            return(img);
        }
        private void InstanceBus_MessageReceived(object sender, TinyMessageReceivedEventArgs e)
        {
            var message = UnwrapMessage(e.Message);

            if (!message.HasValue)
            {
                return;
            }

            LogManager.Debug.Info($"Receive message - name = {message.Value.Name}, " +
                                  $"type = {message.Value.ContentType}, restoreWindow = {message.Value.RestoreWindow}");

            if (message.Value.ContentType == IpcBusContentType.StringUtf8)
            {
                LogManager.Debug.Info($"Receive message content - {message.Value.GetStringUtf8()}");
            }

            if (message.Value.Name == "SendArgs")
            {
                var args    = message.Value.GetStringUtf8().Split(" || ");
                var wrapper = App.UnwrapArgs(args);

                foreach (var argEntry in wrapper.Enumerate())
                {
                    switch (argEntry.Key)
                    {
                    case "startupUri":
                        var startupUri = (string)argEntry.Value;

                        if (!string.IsNullOrEmpty(startupUri))
                        {
                            ProtocolManager.ParseUri(startupUri);
                        }

                        break;

                    case "createHashFiles":
                        var  createHashFilesString = (string)argEntry.Value;
                        bool createHashFiles;

                        try
                        {
                            createHashFiles = string.IsNullOrWhiteSpace(createHashFilesString) ||
                                              createHashFilesString.ToBoolean();
                        }
                        catch (Exception)
                        {
                            createHashFiles = false;
                        }

                        if (createHashFiles)
                        {
                            App.CreateHashFiles();
                        }

                        break;

                    default:
                        break;
                    }
                }
            }
            else
            {
                return;
            }

            if (message.Value.RestoreWindow)
            {
                _ = WindowNative.PostMessage((IntPtr)WindowNative.HwndBroadcast,
                                             SingleInstanceMessage, IntPtr.Zero, IntPtr.Zero);
            }
        }
예제 #26
0
        private void bnSendMessage_Click(object sender, EventArgs e)
        {
            int nNumber;

            // Validate the parameter value in tbNumber
            if (!int.TryParse(this.tbNumber.Text, out nNumber))
            {
                MessageBox.Show("Invalid value of nNumber!");
                return;
            }


            /////////////////////////////////////////////////////////////////
            // Find the target Window Handle.
            //

            IntPtr hTargetWnd = WindowNative.FindWindow(null, "CSReceiveWM_COPYDATA");

            // Validate the Window Handle.
            if (hTargetWnd == IntPtr.Zero)
            {
                MessageBox.Show("Unable to find the target Window!");
                return;
            }


            /////////////////////////////////////////////////////////////////
            // Prepare the COPYDATASTRUCT struct with the data to be sent.
            //

            // Declare the MyStruct struct to hold the message
            MyStruct myStruct;

            myStruct.nNumber    = nNumber;
            myStruct.strMessage = this.tbMessage.Text;

            // Marshals from the managed object to a native block of memory
            IntPtr ptrMyStruct = Marshal.AllocHGlobal(Marshal.SizeOf(myStruct));

            Marshal.StructureToPtr(myStruct, ptrMyStruct, true);

            // Declare the COPYDATASTRUCT struct for the WM_COPYDATA message.
            COPYDATASTRUCT cds = new COPYDATASTRUCT();

            cds.cbData = Marshal.SizeOf(myStruct);
            cds.lpData = ptrMyStruct;


            /////////////////////////////////////////////////////////////////
            // Send the COPYDATASTRUCT struct through the WM_COPYDATA message
            // to the receiving Window.
            //

            // Send the WM_COPYDATA message
            // The application must use SendMessage, instead of PostMessage
            // to send WM_COPYDATA because the receiving application must
            // accept while it is guaranteed to be valid.
            WindowNative.SendMessage(
                hTargetWnd,                 // Handle of the target Window
                WindowNative.WM_COPYDATA,   // WM_COPYDATE message
                this.Handle,                // Handle of the current Window
                ref cds                     // COPYDATASTRUCT structure
                );

            // Check error of SendMessage
            int result = Marshal.GetLastWin32Error();

            if (result != 0)
            {
                MessageBox.Show(String.Format(
                                    "SendMessage failed w/err 0x{0:X}", result));
            }


            /////////////////////////////////////////////////////////////////
            // Clean up.
            //

            // Frees the native memory allocated for MyStruct
            Marshal.FreeHGlobal(ptrMyStruct);
        }
예제 #27
0
 /// <summary>
 /// <paramref name="hWnd"/>의 Text 값을 반환합니다.
 /// </summary>
 /// <param name="hWnd"></param>
 /// <returns></returns>
 public static string GetWindowText(IntPtr hWnd)
 {
     return(WindowNative.GetWindowText(hWnd));
 }
예제 #28
0
 /// <summary>
 /// <paramref name="processId"/>에 해당하는 프로세스의 Window 핸들을 <see cref="System.IntPtr"/> 배열로 반환합니다.
 /// </summary>
 /// <param name="processId"></param>
 /// <returns></returns>
 public static IntPtr[] GetProcessWindowHandles(int processId)
 {
     return(WindowNative.GetProcessWindowHandles(processId));
 }