Example #1
0
        public static void CenterWindowToScreen(IntPtr hwnd, bool useWorkArea = true)
        {
            try
            {
                IntPtr handle = MonitorFromWindow(GetDesktopWindow(), MONITOR_DEFAULTTONEAREST);

                MONITORINFOEX monInfo = new MONITORINFOEX();
                monInfo.cbSize = Marshal.SizeOf(monInfo);
                monInfo.Init();

                GetMonitorInfo(handle, ref monInfo);
                var screenRect = useWorkArea ? monInfo.workArea : monInfo.monitor;
                var midX       = (monInfo.monitor.right - monInfo.monitor.left) / 2;
                var midY       = (monInfo.monitor.bottom - monInfo.monitor.top) / 2;
                var size       = GetWindowSize(hwnd);
                var left       = midX - (size.Width / 2);
                var top        = midY - (size.Height / 2);

                SetWindowPos(
                    hwnd,
                    IntPtr.Zero,
                    left,
                    top,
                    -1,
                    -1,
                    SetWindowPosFlags.DoNotActivate | SetWindowPosFlags.IgnoreResize | SetWindowPosFlags.IgnoreZOrder);
            }
            catch { }
            {
            }
        }
Example #2
0
        public static Rectangle FullScreenBounds(Rectangle configuredBounds)
        {
            try
            {
                IntPtr handle = MonitorFromWindow(GetDesktopWindow(), MONITOR_DEFAULTTONEAREST);

                MONITORINFOEX monInfo = new MONITORINFOEX();
                monInfo.cbSize = Marshal.SizeOf(monInfo);
                monInfo.Init();

                GetMonitorInfo(handle, ref monInfo);

                int left   = monInfo.monitor.left;
                int top    = monInfo.monitor.top;
                int width  = monInfo.monitor.right - monInfo.monitor.left;
                int height = monInfo.monitor.bottom - monInfo.monitor.top;

                if (width <= 0 || height <= 0)
                {
                    return(configuredBounds);
                }

                return(new Rectangle(left, top, width, height));
            }
            catch { }
            {
            }

            return(configuredBounds);
        }
Example #3
0
//		static internal void ListDocuments()
//		{
//			logMsg(_formProjSel.ToString());
//		}


        static internal void ListSystemInformation(IntPtr parent, int titleBarHeight)
        {
            logMsgln("   get win|    title bar height| " + titleBarHeight);

            logMsgln("sys metric| caption area height| " + GetSystemMetrics(SystemMetric.SM_CYCAPTION));
            logMsgln("sys metric|   sm caption height| " + GetSystemMetrics(SystemMetric.SM_CYSMCAPTION));
            logMsgln("sys metric|        border width| " + GetSystemMetrics(SystemMetric.SM_CXBORDER));
            logMsgln("sys metric|       border height| " + GetSystemMetrics(SystemMetric.SM_CYBORDER));
            logMsgln("sys metric|  fixed frame| horiz| " + GetSystemMetrics(SystemMetric.SM_CXFIXEDFRAME));
            logMsgln("sys metric|  fixed frame|  vert| " + GetSystemMetrics(SystemMetric.SM_CYFIXEDFRAME));
            logMsgln("sys metric|   size frame| horiz| " + GetSystemMetrics(SystemMetric.SM_CXSIZEFRAME));
            logMsgln("sys metric|   size frame|  vert| " + GetSystemMetrics(SystemMetric.SM_CYSIZEFRAME));
            logMsgln("sys metric|  window min| height| " + GetSystemMetrics(SystemMetric.SM_CYMIN));
            logMsgln("sys metric|  window min|  width| " + GetSystemMetrics(SystemMetric.SM_CXMIN));

            // this works for getting the correct monitor and the
            // correct monitor location and size
            MONITORINFOEX mi = GetMonitorInfo(parent);

            logMsgln("monitor info|       device name| " + mi.DeviceName);
            logMsgln("monitor info|      monitor rect| " + ListRect(mi.rcMonitor));
            logMsgln("monitor info|    work area rect| " + ListRect(mi.rcWorkArea));
            logMsgln("monitor info|  primary monitor?| " +
                     (mi.Flags == dwFlags.MONITORINFO_PRIMARY));

            logMsgln(nl);
            logMsgln("monitor DPI| " + GetDpiForWindow(parent));
        }
Example #4
0
        public static Rect CheckScreenRect(IntPtr windowHandle)
        {
            Rect rect = new Rect();

            if (windowHandle == IntPtr.Zero)
            {
                return(rect);
            }

            IntPtr        hMonitor    = DpiUtil.MonitorFromWindow(windowHandle, DpiUtil.MONITOR_DEFAULTTONEAREST);
            MONITORINFOEX monitorInfo = DisplayUtil.CreateMonitorInfo();
            int           result      = DisplayUtil.GetMonitorInfo(hMonitor, ref monitorInfo);

            if (result == 0)
            {
                log.Error("failed to get monitor info");
                return(rect);
            }

            DisplayUtil.DEVMODE dm = DisplayUtil.CreateDevmode();
            if (0 != DisplayUtil.EnumDisplaySettings(
                    monitorInfo.szDevice,
                    DisplayUtil.ENUM_CURRENT_SETTINGS,
                    ref dm))
            {
                rect = new Rect(dm.dmPositionX, dm.dmPositionY, dm.dmPelsWidth, dm.dmPelsHeight);
                log.WarnFormat("CheckScreenRect: {0}, {1}, {2}, {3}, {4}", monitorInfo.szDevice, dm.dmPositionX, dm.dmPositionY, dm.dmPelsWidth, dm.dmPelsHeight);
            }
            return(rect);
        }
Example #5
0
        private static void calcScaleFactorForMonitor(IntPtr hWnd, out double horzScale, out double vertScale)
        {
            // Get the monitor that the window is currently displayed on
            // (where hWnd is a handle to the window of interest).
            IntPtr hMonitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST);

            // Get the logical width and height of the monitor.
            MONITORINFOEX miex = new MONITORINFOEX();

            GetMonitorInfo(hMonitor, miex);
            int cxLogical = (miex.rcMonitor.right - miex.rcMonitor.left);
            int cyLogical = (miex.rcMonitor.bottom - miex.rcMonitor.top);

            // Get the physical width and height of the monitor.
            DEVMODE dm = new DEVMODE();

            dm.dmSize        = (short)Marshal.SizeOf(typeof(DEVMODE));
            dm.dmDriverExtra = 0;

            string devname = new String(miex.szDevice);

            EnumDisplaySettings(devname, ENUM_CURRENT_SETTINGS, ref dm);
            int cxPhysical = dm.dmPelsWidth;
            int cyPhysical = dm.dmPelsHeight;

            // Calculate the scaling factor.
            horzScale = ((double)cxPhysical / (double)cxLogical);
            vertScale = ((double)cyPhysical / (double)cyLogical);
        }
Example #6
0
        public static HandleItem[] GetMonitorHandles()
        {
            var handleItems = new List <HandleItem>();

            if (!EnumDisplayMonitors(
                    IntPtr.Zero,
                    IntPtr.Zero,
                    MonitorEnum,
                    IntPtr.Zero))
            {
                return(Array.Empty <HandleItem>());
            }

            bool MonitorEnum(IntPtr hMonitor, IntPtr hdcMonitor, IntPtr lprcMonitor, IntPtr dwData)
            {
                var monitorInfo = new MONITORINFOEX {
                    cbSize = (uint)Marshal.SizeOf <MONITORINFOEX>()
                };

                if (!GetMonitorInfo(hMonitor, ref monitorInfo))
                {
                    Debug.WriteLine($"Failed to get information on a display monitor.");
                }
                else if (TryGetDisplayIndex(monitorInfo.szDevice, out byte displayIndex))
                {
                    handleItems.Add(new HandleItem(
                                        monitorHandle: hMonitor,
                                        displayIndex: displayIndex));
                }
                return(true);
            }

            return(handleItems.ToArray());
        }
Example #7
0
        public static void SetFullscreen(this Window window)
        {
            // Make window borderless
            window.WindowStyle = WindowStyle.None;
            window.ResizeMode  = ResizeMode.NoResize;

            // Get handle for nearest monitor to this window
            WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window);
            IntPtr nearestMonitor = MonitorFromWindow(windowInteropHelper.Handle, monitorDefaultToNearest);

            // Get monitor info
            MONITORINFOEX monitorInfo = new MONITORINFOEX();

            monitorInfo.cbSize = Marshal.SizeOf(monitorInfo);
            GetMonitorInfo(new HandleRef(window, nearestMonitor), monitorInfo);

            // Create working area dimensions, converted to DPI-independent values
            HwndSource source = HwndSource.FromHwnd(windowInteropHelper.Handle);

            if (source == null || source.CompositionTarget == null)
            {
                return;
            }

            Matrix matrix             = source.CompositionTarget.TransformFromDevice;
            RECT   workingArea        = monitorInfo.rcMonitor;
            Point  dpiIndependentSize = matrix.Transform(new Point(workingArea.Right - workingArea.Left,
                                                                   workingArea.Bottom - workingArea.Top));

            window.MaxWidth    = dpiIndependentSize.X;
            window.MaxHeight   = dpiIndependentSize.Y;
            window.WindowState = WindowState.Maximized;
        }
Example #8
0
        private void MaximizeWindow(bool maximize)
        {
            if (!MaximizeBox || !ControlBox)
            {
                return;
            }

            _maximized = maximize;

            if (maximize)
            {
                var monitorHandle = MonitorFromWindow(Handle, MONITOR_DEFAULTTONEAREST);
                var monitorInfo   = new MONITORINFOEX();
                GetMonitorInfo(new HandleRef(null, monitorHandle), monitorInfo);
                _previousSize     = Size;
                _previousLocation = Location;
                Size     = new Size(monitorInfo.rcWork.Width(), monitorInfo.rcWork.Height());
                Location = new Point(monitorInfo.rcWork.left, monitorInfo.rcWork.top);
            }
            else
            {
                Size     = _previousSize;
                Location = _previousLocation;
            }
        }
Example #9
0
        public static HandleItem[] GetMonitorHandles()
        {
            var handleItems = new List <HandleItem>();

            if (EnumDisplayMonitors(
                    IntPtr.Zero,
                    IntPtr.Zero,
                    Proc,
                    IntPtr.Zero))
            {
                return(handleItems.ToArray());
            }
            return(Array.Empty <HandleItem>());

            bool Proc(IntPtr monitorHandle, IntPtr hdcMonitor, IntPtr lprcMonitor, IntPtr dwData)
            {
                var monitorInfo = new MONITORINFOEX {
                    cbSize = (uint)Marshal.SizeOf <MONITORINFOEX>()
                };

                if (GetMonitorInfo(
                        monitorHandle,
                        ref monitorInfo))
                {
                    if (TryGetDisplayIndex(monitorInfo.szDevice, out byte displayIndex))
                    {
                        handleItems.Add(new HandleItem(
                                            displayIndex: displayIndex,
                                            monitorRect: monitorInfo.rcMonitor,
                                            monitorHandle: monitorHandle));
                    }
                }
                return(true);
            }
        }
Example #10
0
        public static IList <MonitorInfo> GetScreens()
        {
            var screens = new List <MonitorInfo>();

            Native.EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, delegate(IntPtr hMonitor, IntPtr hdcMonitor, ref Native.RECT lprcMonitor, IntPtr dwData)
            {
                var mi = new MONITORINFOEX();

                if (GetMonitorInfo(hMonitor, mi))
                {
                    var deviceName = new string(mi.szDevice.Where(_ => _ != (char)0).ToArray());

                    screens.Add(new MonitorInfo
                    {
                        ScreenSize  = new Size(mi.rcMonitor.Right - mi.rcMonitor.Left, mi.rcMonitor.Bottom - mi.rcMonitor.Top),
                        MonitorArea = new Rect(mi.rcMonitor.Left, mi.rcMonitor.Top, mi.rcMonitor.Right - mi.rcMonitor.Left, mi.rcMonitor.Bottom - mi.rcMonitor.Top),
                        WorkArea    = new Rect(mi.rcWork.Left, mi.rcWork.Top, mi.rcWork.Right - mi.rcWork.Left, mi.rcWork.Bottom - mi.rcWork.Top),
                        IsPrimary   = mi.dwFlags > 0,
                        HMon        = hMonitor,
                        DeviceName  = deviceName.StartsWith("\\\\.\\") ? deviceName.Substring(4) : deviceName
                    });
                }

                return(true);
            }, IntPtr.Zero);

            return(screens);
        }
Example #11
0
        private void MaximizeWindow(bool maximize)
        {
            if (!MaximizeBox || !ControlBox)
            {
                return;
            }

            Maximized = maximize;

            if (maximize)
            {
                IntPtr        monitorHandle = MonitorFromWindow(Handle, MONITOR_DEFAULTTONEAREST);
                MONITORINFOEX monitorInfo   = new MONITORINFOEX();
                GetMonitorInfo(new HandleRef(null, monitorHandle), monitorInfo);
                previousSize     = Size;
                previousLocation = Location;
                Size             = new Size(monitorInfo.rcWork.Width(), monitorInfo.rcWork.Height());
                Location         = new Point(monitorInfo.rcWork.left, monitorInfo.rcWork.top);
            }
            else
            {
                Size     = previousSize;
                Location = previousLocation;
            }
            //Raise an event to allow forms to do something when we maximise the form
            if (Maximise != null)
            {
                Maximise((object)this, new EventArgs());
            }
        }
Example #12
0
        private static void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
        {
            var mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

            // Adjust the maximized size and position to fit the work area of the correct monitor

            var monitor = NativeMethods.MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

            if (monitor != IntPtr.Zero)
            {
                var monitorInfo = new MONITORINFOEX {
                    cbSize = Marshal.SizeOf(typeof(MONITORINFOEX))
                };

                NativeMethods.GetMonitorInfo(monitor, ref monitorInfo);
                var rcWorkArea    = monitorInfo.rcWork;
                var rcMonitorArea = monitorInfo.rcMonitor;

                mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
                mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
                mmi.ptMaxSize.x     = Math.Abs(rcWorkArea.right - rcWorkArea.left);
                mmi.ptMaxSize.y     = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
            }

            Marshal.StructureToPtr(mmi, lParam, true);
        }
Example #13
0
        private ScreenInterop(IntPtr monitor, IntPtr hdc)
        {
            if (!MultiMonitorSupport || monitor == (IntPtr)PRIMARY_MONITOR)
            {
                this.Bounds     = new Rect(SystemParameters.VirtualScreenLeft, SystemParameters.VirtualScreenTop, SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight);
                this.Primary    = true;
                this.DeviceName = "DISPLAY";
            }
            else
            {
                var info = new MONITORINFOEX();

                GetMonitorInfo(new HandleRef(null, monitor), info);

                this.Bounds = new Rect(
                    info.rcMonitor.left, info.rcMonitor.top,
                    info.rcMonitor.right - info.rcMonitor.left,
                    info.rcMonitor.bottom - info.rcMonitor.top);

                this.Primary = ((info.dwFlags & MONITORINFOF_PRIMARY) != 0);

                this.DeviceName = new string(info.szDevice).TrimEnd((char)0);
            }
            hmonitor = monitor;
        }
Example #14
0
        public static Rect[] GetMonitorsWorkingAreas()
        {
            try
            {
                List <IntPtr> monitors = new List <IntPtr>();
                Checked(1, "EnumDisplayMonitors", EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, (a, b, c, d) => { monitors.Add(a); return(true); }, IntPtr.Zero));

                return(monitors.Select(handle =>
                {
                    Checked(0, "GetDpiForMonitor", GetDpiForMonitor(handle, 0, out var x, out var y));
                    MONITORINFOEX info = new MONITORINFOEX();
                    Checked(1, "GetMonitorInfo", GetMonitorInfo(new HandleRef(null, handle), info));

                    var rc = info.rcWork;
                    var dpiX = x / 96.0;
                    var dpiY = y / 96.0;
                    return new Rect(rc.left / dpiX, rc.top / dpiX, (rc.right - rc.left) / dpiX, (rc.bottom - rc.top) / dpiY);
                }).ToArray());
            }
            catch (Exception e)
            {
                Log.Warning(e, "GetMonitorsWorkingAreas failed");
                return(null);
            }
        }
Example #15
0
        private Screen(IntPtr monitor, IntPtr hdc)
        {
            if (!multiMonitorSupport || monitor == (IntPtr)PRIMARY_MONITOR)
            {
                Bounds     = VirtualScreen;
                IsPrimary  = true;
                DeviceName = "DISPLAY";
            }
            else
            {
                var info = new MONITORINFOEX();

                GetMonitorInfo(new HandleRef(null, monitor), info);

                Bounds = new(
                    info.rcMonitor.Left, info.rcMonitor.Top,
                    info.rcMonitor.Right - info.rcMonitor.Left,
                    info.rcMonitor.Bottom - info.rcMonitor.Top);

                IsPrimary = ((info.dwFlags & MONITORINFOF_PRIMARY) != 0);

                DeviceName = new string(info.szDevice).TrimEnd((char)0);
            }
            hmonitor = monitor;
        }
Example #16
0
 internal MonitorInfo(MONITORINFOEX mex)
 {
     ViewportBounds = (Rect)mex.rcMonitor;
     WorkAreaBounds = (Rect)mex.rcWork;
     IsPrimary      = mex.dwFlags.HasFlag(ShellApi.MonitorInfoOf.PRIMARY);
     DeviceId       = mex.szDevice;
 }
Example #17
0
        void MainWindow_SourceInitialized(object sender, EventArgs e)
        {
            WindowBehavior.ExtendGlassFrame(this, new Thickness(0, 26, 0, 0));
            WindowInteropHelper wih   = new WindowInteropHelper(this);
            IntPtr        hMonitor    = MonitorFromWindow(wih.Handle, MONITOR_DEFAULTTONEAREST);
            MONITORINFOEX monitorInfo = new MONITORINFOEX();

            monitorInfo.cbSize = Marshal.SizeOf(monitorInfo);
            GetMonitorInfo(new HandleRef(this, hMonitor), monitorInfo);
            HwndSource source = HwndSource.FromHwnd(wih.Handle);

            if (source == null)
            {
                return;
            }
            if (source.CompositionTarget == null)
            {
                return;
            }
            Matrix matrix             = source.CompositionTarget.TransformFromDevice;
            RECT   workingArea        = monitorInfo.rcWork;
            Point  dpiIndependentSize =
                matrix.Transform(
                    new Point(
                        workingArea.Right - workingArea.Left,
                        workingArea.Bottom - workingArea.Top));

            this.Top    = dpiIndependentSize.Y - this.ActualHeight - 10;
            this.Height = this.ActualHeight;
            this.Left   = dpiIndependentSize.X - this.ActualWidth - 10;
            this.Width  = this.ActualWidth;
            source.AddHook(WndProc);
        }
Example #18
0
        public void HandleForegroundWindowChange(string processName, IntPtr hwnd)
        {
            var dict = ConfigManager.Instance.Config.ProcessConfigs.Where(c => c.BorderlessWindow).ToDictionary(c => c.ProcessName, c => c.BorderlessOffset);

            if (dict.ContainsKey(processName))
            {
                GetWindowRect(hwnd, out RECT rect);
                //Bot Left Right Top
                //1441,-3,3443,-5
                //1469,0,3446,0
                //3440 1440

                var monHandle = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
                var monInfo   = new MONITORINFOEX();
                monInfo.Size = Marshal.SizeOf(monInfo);
                GetMonitorInfo(monHandle, ref monInfo);

                //right - left is width, bottom - top is height
                var xOffset = monInfo.Monitor.Right - (rect.Right - rect.Left) + _borderWidth + dict[processName];
                var yOffset = monInfo.Monitor.Bottom - (rect.Bottom - rect.Top) + _borderWidth + dict[processName];

                // Move the window to (0,0) without changing its size or position in the Z order.
                SetWindowPos(hwnd, IntPtr.Zero, xOffset, yOffset, 0, 0, SWP_NOSIZE);
            }
        }
Example #19
0
        /// <summary>
        /// 最大化
        /// </summary>
        /// <param name="maximize"></param>
        public void MaximizeWindow(bool maximize)
        {
            if (!MaximizeBox)
            {
                return;
            }

            K_IsMaximized = maximize;

            if (maximize)
            {
                IntPtr        monitorHandle = MonitorFromWindow(Handle, MONITOR_DEFAULTTONEAREST);
                MONITORINFOEX monitorInfo   = new MONITORINFOEX();
                GetMonitorInfo(new HandleRef(null, monitorHandle), monitorInfo);
                previousSize     = Size;
                previousLocation = Location;
                Size             = new Size(monitorInfo.rcWork.Width(), monitorInfo.rcWork.Height());
                Location         = new Point(monitorInfo.rcWork.left, monitorInfo.rcWork.top);

                SetReion(1);
            }
            else
            {
                Size     = previousSize;
                Location = previousLocation;

                SetReion(3);
            }
            if (K_WindowStateChanged != null)
            {
                K_WindowStateChanged(this, new EventArgs());
            }
        }
Example #20
0
        private static DisplayConfig GetDisplayConfig()
        {
            int       w       = GetSystemMetrics(CX_VIRTUALSCREEN);
            int       h       = GetSystemMetrics(CY_VIRTUALSCREEN);
            Rectangle vBounds = new Rectangle(0, 0, 0, 0);

            List <Display> displays = new List <Display>();

            EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero,
                                delegate(IntPtr hMonitor, IntPtr hdcMonitor, ref W32Rect lprcMonitor, IntPtr dwData)
            {
                MONITORINFOEX mi = new MONITORINFOEX();
                mi.Size          = Marshal.SizeOf(mi);
                int displayIndex = 1;
                if (GetMonitorInfo(hMonitor, ref mi))
                {
                    Rectangle r = Rectangle.FromLTRB(mi.Monitor.left, mi.Monitor.top, mi.Monitor.right, mi.Monitor.bottom);
                    vBounds     = Rectangle.Union(vBounds, r);
                    displays.Add(new Display(r, displayIndex, mi.DeviceName, (mi.Flags != 0)));
                    displayIndex++;
                }
                return(true);
            }, IntPtr.Zero);

            return(new DisplayConfig(vBounds, displays));
        }
Example #21
0
 internal MonitorInformation(MONITORINFOEX mex)
 {
     this.ViewportBounds = (Rect)mex.rcMonitor;
     this.WorkAreaBounds = (Rect)mex.rcWork;
     this.IsPrimary      = mex.dwFlags.HasFlag(MONITORINFOF.PRIMARY);
     this.DeviceId       = mex.szDevice;
 }
Example #22
0
        void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
        {
            // MINMAXINFO structure
            MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

            //拿到最靠近当前软件的显示器
            IntPtr hMonitor = NativeMethods.MonitorFromWindow(Handle, NativeConstants.MONITOR_DEFAULTTONEAREST);

            // Get monitor info   显示屏
            MONITORINFOEX monitorInfo = new MONITORINFOEX();

            monitorInfo.cbSize = Marshal.SizeOf(monitorInfo);
            NativeMethods.GetMonitorInfo(new HandleRef(this, hMonitor), monitorInfo);

            // Convert working area
            RECT workingArea = monitorInfo.rcWork;

            //设置最大化的时候的坐标
            mmi.ptMaxPosition.x = 0; // workingArea.left;
            mmi.ptMaxPosition.y = 0; // workingArea.top;

            if (source == null)
            {
                throw new Exception("Cannot get HwndSource instance.");
            }
            if (source.CompositionTarget == null)
            {
                throw new Exception("Cannot get HwndTarget instance.");
            }

            Matrix matrix = source.CompositionTarget.TransformToDevice;

            Point dpiIndenpendentTrackingSize = matrix.Transform(new Point(
                                                                     this.MinWidth,
                                                                     this.MinHeight));

            if (FullScreen)
            {
                Point dpiSize = matrix.Transform(new Point(
                                                     SystemParameters.PrimaryScreenWidth,
                                                     SystemParameters.PrimaryScreenHeight
                                                     ));

                mmi.ptMaxSize.x = (int)dpiSize.X;
                mmi.ptMaxSize.y = (int)dpiSize.Y;
            }
            else
            {
                //设置窗口最大化的尺寸
                mmi.ptMaxSize.x = workingArea.right - workingArea.left;
                mmi.ptMaxSize.y = workingArea.bottom;
            }

            //设置最小跟踪大小
            mmi.ptMinTrackSize.x = (int)dpiIndenpendentTrackingSize.X;
            mmi.ptMinTrackSize.y = (int)dpiIndenpendentTrackingSize.Y;

            Marshal.StructureToPtr(mmi, lParam, true);
        }
Example #23
0
 public static unsafe bool GetMonitorInfo(
     IntPtr hMonitor,
     out MONITORINFOEX lpmi)
 {
     fixed(MONITORINFOEX *lpmiLocal = &lpmi)
     {
         return(GetMonitorInfo(hMonitor, lpmiLocal));
     }
 }
Example #24
0
            public static MONITORINFOEX New()
            {
                var item = new MONITORINFOEX();

                item.Size       = 40 + 2 * CCHDEVICENAME;
                item.Flags      = 0;
                item.DeviceName = string.Empty;
                return(item);
            }
        /// <summary>
        /// Gets color profile file path used by the monitor to which a specified Window belongs.
        /// </summary>
        /// <param name="window">Source Window</param>
        /// <returns>Color profile file path</returns>
        public static string GetColorProfilePath(Visual window)
        {
            var source = PresentationSource.FromVisual(window) as HwndSource;

            if (source is null)
            {
                return(null);
            }

            var monitorHandle = MonitorFromWindow(
                source.Handle,
                MONITOR_DEFAULTTO.MONITOR_DEFAULTTONEAREST);

            var monitorInfo = new MONITORINFOEX {
                cbSize = (uint)Marshal.SizeOf <MONITORINFOEX>()
            };

            if (!GetMonitorInfo(monitorHandle, ref monitorInfo))
            {
                return(null);
            }

            var deviceHandle = IntPtr.Zero;

            try
            {
                deviceHandle = CreateDC(
                    monitorInfo.szDevice,
                    monitorInfo.szDevice,
                    null,
                    IntPtr.Zero);
                if (deviceHandle == IntPtr.Zero)
                {
                    return(null);
                }

                // The maximum file path length is 260 which is defined as MAX_PATH. It may be longer in Unicode
                // versions of some functions while no detailed information on GetICMProfileW.
                var lpcbName = 260U;
                while (true)
                {
                    var buffer = new StringBuilder((int)lpcbName);
                    if (GetICMProfile(deviceHandle, ref lpcbName, buffer))
                    {
                        return(buffer.ToString());
                    }
                }
            }
            finally
            {
                if (deviceHandle != IntPtr.Zero)
                {
                    DeleteDC(deviceHandle);
                }
            }
        }
Example #26
0
        internal Screen(IntPtr monitor, IntPtr hdc)
        {
            var info = new MONITORINFOEX();
            GetMonitorInfo(new HandleRef(null, monitor), info);

            Bounds = RectFromLTRB(info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.right, info.rcMonitor.bottom);
            WorkingArea = RectFromLTRB(info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom);
            IsPrimary = ((info.dwFlags & MONITORINFOF_PRIMARY) != 0);
            Name = new string(info.szDevice).TrimEnd((char)0);
        }
Example #27
0
        public static MONITORINFOEX CreateMonitorInfo()
        {
            MONITORINFOEX monitorInfo = new MONITORINFOEX();

            monitorInfo.cbSize    = (int)Marshal.SizeOf(monitorInfo);
            monitorInfo.rcMonitor = new RECT();
            monitorInfo.rcWork    = new RECT();
            monitorInfo.szDevice  = new String(new char[32]);
            return(monitorInfo);
        }
Example #28
0
 public ScreenInfo(IntPtr hmon, MONITORINFOEX monitorInfoEx, float displayScale)
 {
     Hmon         = hmon;
     Left         = monitorInfoEx.Monitor.Left;
     Top          = monitorInfoEx.Monitor.Top;
     Right        = monitorInfoEx.Monitor.Right;
     Bottom       = monitorInfoEx.Monitor.Bottom;
     DisplayScale = displayScale;
     IsPrimary    = monitorInfoEx.Flags > 0;
 }
Example #29
0
        }         // WndProc()

        private void UpdateDisplaySet()
        {
            MONITORINFOEX monitorInfo  = new MONITORINFOEX();
            List <string> displaySetId = new List <string>();
            int           counter      = 0;

            monitorInfo.length = 104;

            EnumDisplayMonitors(
                IntPtr.Zero,
                IntPtr.Zero,
                delegate(IntPtr hMonitor, IntPtr hdc, ref RECT pRect, int dwData)
            {
                GetMonitorInfo(hMonitor, ref monitorInfo);

                StringBuilder id = new StringBuilder();

                if ((monitorInfo.flags & MONITORINFO_PRIMARY) == MONITORINFO_PRIMARY)
                {
                    id.Append("(P)");
                }
                id.Append(++counter);
                id.Append(':');
                id.Append(pRect.right);
                id.Append('×');
                id.Append(pRect.bottom);
                if (pRect.left != 0 || pRect.top != 0)
                {
                    id.Append('@');
                    id.Append(pRect.left);
                    id.Append('×');
                    id.Append(pRect.top);
                }

                displaySetId.Add(id.ToString());

                return(true);
            },
                0
                );

            _displaySet = string.Join(", ", displaySetId);

            if (_displaySets.ContainsKey(_displaySet))
            {
                _displaySets[_displaySet].Save();
            }
            else
            {
                _displaySets.Add(_displaySet, new WindowTracker());
            }

            MnuCurrent.Text = _displaySet;
        }         // UpdateDisplaySet()
Example #30
0
        internal Screen(IntPtr monitor, IntPtr hdc)
        {
            var info = new MONITORINFOEX();

            GetMonitorInfo(new HandleRef(null, monitor), info);

            Bounds      = RectFromLTRB(info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.right, info.rcMonitor.bottom);
            WorkingArea = RectFromLTRB(info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom);
            IsPrimary   = ((info.dwFlags & MONITORINFOF_PRIMARY) != 0);
            Name        = new string(info.szDevice).TrimEnd((char)0);
        }
Example #31
0
        internal static MONITORINFOEX GetMonitorInfo(IntPtr parent)
        {
            IntPtr hMonitor = MonitorFromWindow(parent, 0);

            MONITORINFOEX mi = new MONITORINFOEX();

            mi.Init();
            GetMonitorInfo(hMonitor, ref mi);

            return(mi);
        }
        public void MaximizeWindow(bool maximize)
        {
            if (!MaximizeBox || !ControlBox) return;

            Maximized = maximize;

            if (maximize)
            {
                IntPtr monitorHandle = MonitorFromWindow(Handle, MONITOR_DEFAULTTONEAREST);
                MONITORINFOEX monitorInfo = new MONITORINFOEX();
                GetMonitorInfo(new HandleRef(null, monitorHandle), monitorInfo);
                previousSize = Size;
                previousLocation = Location;
                Size = new Size(monitorInfo.rcWork.Width(), monitorInfo.rcWork.Height());
                Location = new Point(monitorInfo.rcWork.left, monitorInfo.rcWork.top);
            }
            else
            {
                Size = previousSize;
                Location = previousLocation;
            }

        }
Example #33
0
 internal static extern bool GetMonitorInfo(int hMonitor, ref MONITORINFOEX lpmi);
Example #34
0
		static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFOEX lpmi);
Example #35
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="o">Dependency object attached somewhere in a <see cref="Window"/> or the <see cref="Window"/> object itself</param>
		public Screen(DependencyObject o) {
			var helper = GetHelper(o);
			IsValid = false;
			info = default(MONITORINFOEX);
			if (helper != null) {
				var hMonitor = MonitorFromWindow(helper.Handle, MONITOR_DEFAULTTONEAREST);
				info.cbSize = MONITORINFOEX.SIZE;
				if (!GetMonitorInfo(hMonitor, ref info))
					info = default(MONITORINFOEX);
				else
					IsValid = true;
			}
		}
 internal static MONITORINFOEX GetDesktopBoundsForWindow(IntPtr handle)
     {
     IntPtr ptr = MonitorFromWindow(handle, (uint) Enums.MonitorFromWindow_Flags.MONITOR_DEFAULTTONEAREST);
     MONITORINFOEX m = new MONITORINFOEX();
     GetMonitorInfo(ptr, m);
     return m;
     }
Example #37
0
        private static void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam) {
            var mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

            // Adjust the maximized size and position to fit the work area of the correct monitor

            var monitor = NativeMethods.MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

            if (monitor != IntPtr.Zero) {
                var monitorInfo = new MONITORINFOEX {
                    cbSize = Marshal.SizeOf(typeof(MONITORINFOEX))
                };

                NativeMethods.GetMonitorInfo(monitor, ref monitorInfo);
                var rcWorkArea = monitorInfo.rcWork;
                var rcMonitorArea = monitorInfo.rcMonitor;

                mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
                mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
                mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
                mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
            }

            Marshal.StructureToPtr(mmi, lParam, true);
        }
Example #38
0
 public static extern bool GetMonitorInfo(IntPtr hmonitor, ref MONITORINFOEX monitorInfo);
Example #39
0
        private void UpdateWindowBounds() {
            if (WindowState == WindowState.Normal) {
                BorderThickness = new Thickness(1);
                FramePadding = new Thickness(0);
                return;
            }

            var monitor = SafeNativeMethods.MonitorFromWindow(_hwndSource.Handle, MONITOR_DEFAULTTONEAREST);
            var info = new MONITORINFOEX { cbSize = Marshal.SizeOf(typeof(MONITORINFOEX)) };
            SafeNativeMethods.GetMonitorInfo(new HandleRef(this, monitor), ref info);

            if (_hwndSource.CompositionTarget == null) {
                throw new NullReferenceException("_hwndSource.CompositionTarget == null");
            }

            // All points queried from the Win32 API are not DPI aware.
            // Since WPF is DPI aware, one WPF pixel does not necessarily correspond to a device pixel.
            // In order to convert device pixels (Win32 API) into screen independent pixels (WPF), 
            // the following transformation must be applied to points queried using the Win32 API.
            var matrix = _hwndSource.CompositionTarget.TransformFromDevice;

            // Not DPI aware
            var workingArea = info.rcWork;
            var monitorRect = info.rcMonitor;

            // DPI aware
            var bounds = matrix.Transform(new Point(workingArea.right - workingArea.left,
                    workingArea.bottom - workingArea.top));

            // DPI aware
            var origin = matrix.Transform(new Point(workingArea.left, workingArea.top))
                - matrix.Transform(new Point(monitorRect.left, monitorRect.top));

            // Calulates the offset required to adjust the anchor position for the missing client frame border.
            // An additional -1 must be added to the top to perfectly fit the screen, reason is of yet unknown.
            var left = SystemParameters.WindowNonClientFrameThickness.Left
                + SystemParameters.ResizeFrameVerticalBorderWidth + origin.X;
            var top = SystemParameters.WindowNonClientFrameThickness.Top
                + SystemParameters.ResizeFrameHorizontalBorderHeight
                - SystemParameters.CaptionHeight + origin.Y - 1;

            FramePadding = new Thickness(left, top, 0, 0);
            MaxWidth = bounds.X + SystemParameters.ResizeFrameVerticalBorderWidth + SystemParameters.WindowNonClientFrameThickness.Right;
            MaxHeight = bounds.Y + SystemParameters.ResizeFrameHorizontalBorderHeight + SystemParameters.WindowNonClientFrameThickness.Bottom;
            BorderThickness = new Thickness(0);
        }
Example #40
0
 public static extern bool GetMonitorInfo(HandleRef hmonitor, ref MONITORINFOEX monitorInfo);