protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); IntPtr handle = new WindowInteropHelper(this).Handle; HwndSource.FromHwnd(handle).AddHook(new HwndSourceHook(this.JumpResizeProc)); }
public SparkleSetupWindow() { Title = "SparkleShare Setup"; Width = 640; Height = 440; ResizeMode = ResizeMode.NoResize; Background = new SolidColorBrush (Colors.WhiteSmoke); Icon = SparkleUIHelpers.GetImageSource ("sparkleshare-app", "ico"); TaskbarItemInfo = new TaskbarItemInfo () { Description = "SparkleShare" }; WindowStartupLocation = WindowStartupLocation.CenterScreen; Content = ContentCanvas; // Remove the close button Closing += Close; SourceInitialized += delegate { const int gwl_style = -16; const int ws_sysmenu = 0×00080000; WindowInteropHelper helper = new WindowInteropHelper (this); int style = GetWindowLong (helper.Handle, gwl_style); SetWindowLong (helper.Handle, gwl_style, style & ~ws_sysmenu); }; this.bar = new Rectangle () { Width = Width, Height = 40, Fill = new SolidColorBrush (Color.FromRgb (240, 240, 240)) }; this.line = new Rectangle () { Width = Width, Height = 1, Fill = new SolidColorBrush (Color.FromRgb (223, 223, 223)) }; this.side_splash = new Image () { Width = 150, Height = 482 }; this.side_splash.Source = SparkleUIHelpers.GetImageSource ("side-splash"); ContentCanvas.Children.Add (this.bar); Canvas.SetRight (bar, 0); Canvas.SetBottom (bar, 0); ContentCanvas.Children.Add (this.line); Canvas.SetRight (this.line, 0); Canvas.SetBottom (this.line, 40); ContentCanvas.Children.Add (this.side_splash); Canvas.SetLeft (this.side_splash, 0); Canvas.SetBottom (this.side_splash, 0); }
private void UnregisterHotKey() { var helper = new WindowInteropHelper(this); UnregisterHotKey(helper.Handle, HOTKEY_ID); }
private void Window_SourceInitialized(object sender, EventArgs e) { helper = new WindowInteropHelper(this); HwndSource.FromHwnd(helper.Handle).AddHook(new HwndSourceHook(WndProc)); Shell.HideWindowFromTasks(helper.Handle); }
static IntPtr \u206C([In] WindowInteropHelper obj0) { return(obj0.Handle); }
public static void Initialize(MainWindow window) { IntPtr handle = new WindowInteropHelper(window).Handle; IsAvailable = false; // clear devices Devices.Clear(); ContInfoFromLog = LogParser.Instance.GetAttachedControllers(true).Where(a => a.Type == ControllerType.XInput).ToArray(); try { //some users wont even have xinput installed. in order to avoid spurious exceptions and possible instability, check for the library first HasGetInputStateEx = true; LibraryHandle = NativeMethods.LoadLibrary("xinput1_3.dll"); // Win32.LoadLibrary("xinput1_3.dll"); if (LibraryHandle == IntPtr.Zero) { LibraryHandle = NativeMethods.LoadLibrary("xinput1_4.dll"); } if (LibraryHandle == IntPtr.Zero) { LibraryHandle = NativeMethods.LoadLibrary("xinput9_1_0.dll"); HasGetInputStateEx = false; } if (LibraryHandle != IntPtr.Zero) { if (HasGetInputStateEx) { IntPtr proc = GetProcAddressOrdinal(LibraryHandle, new IntPtr(100)); XInputGetStateExProc = (XInputGetStateExProcDelegate)Marshal.GetDelegateForFunctionPointer(proc, typeof(XInputGetStateExProcDelegate)); } //don't remove this code. it's important to catch errors on systems with broken xinput installs. //(probably, checking for the library was adequate, but lets not get rid of this anyway) var test = new SlimDX.XInput.Controller(UserIndex.One).IsConnected; IsAvailable = true; } } catch { } if (!IsAvailable) { return; } //now, at this point, slimdx may be using one xinput, and we may be using another //i'm not sure how slimdx picks its dll to bind to. //i'm not sure how troublesome this will be //maybe we should get rid of slimdx for this altogether var c1 = new Controller(UserIndex.One); var c2 = new Controller(UserIndex.Two); var c3 = new Controller(UserIndex.Three); var c4 = new Controller(UserIndex.Four); try { string error = "WARNING\n\nYou have one or more XInput gamepads/joypads that have been detected, but we couldnt find a mednafen ID for them\n\n" + "Please check stdout.txt for any errors. You must correct them before trying to RE-POLL devices again."; if (c1.IsConnected) { if (ContInfoFromLog.Length < 1) { MessagePopper.ShowMessageDialog(error, "GAMEPAD DETECTION ISSUE"); } Devices.Add(new GamePad360(0, c1, ContInfoFromLog[0])); } if (c2.IsConnected) { if (ContInfoFromLog.Length < 2) { MessagePopper.ShowMessageDialog(error, "GAMEPAD DETECTION ISSUE"); } Devices.Add(new GamePad360(1, c2, ContInfoFromLog[1])); } if (c3.IsConnected) { if (ContInfoFromLog.Length < 3) { MessagePopper.ShowMessageDialog(error, "GAMEPAD DETECTION ISSUE"); } Devices.Add(new GamePad360(2, c3, ContInfoFromLog[2])); } if (c4.IsConnected) { if (ContInfoFromLog.Length < 4) { MessagePopper.ShowMessageDialog(error, "GAMEPAD DETECTION ISSUE"); } Devices.Add(new GamePad360(3, c4, ContInfoFromLog[3])); } } catch (Exception) { } }
static void ShowCloseButton(Window w) { var hwnd = new WindowInteropHelper(w).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_SYSMENU); }
/// <summary> /// Resizes the window to the desired Rect /// Called when WindowRect DependencyProperty changes /// </summary> /// <param name="value">The target Rect containing size and Position</param> private void ResizeWindow(Rect value) { IntPtr windowPtr = new WindowInteropHelper(this).Handle; MoveWindow(windowPtr, (int)value.Left, (int)value.Top, (int)value.Width, (int)value.Height, true); }
static void SendWpfWindowPos(Window window, IntPtr place) { var hWnd = new WindowInteropHelper(window).Handle; SetWindowPos(hWnd, place, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); }
/// <summary> /// Initializes a new instance of <see cref="BorderlessWindow"/> /// </summary> public BorderlessWindow() { this.helper = new WindowInteropHelper(this); }
/// <summary> /// Return WinApi window handler from WPF window /// </summary> /// <param name="w"></param> /// <returns></returns> protected static IntPtr p_GetHW(Window w) { var helper = new WindowInteropHelper(w); return(helper.Handle); }
public SetupWindow() { Title = "SparkleShare Setup"; Width = 640; Height = 440; ResizeMode = ResizeMode.NoResize; Background = new SolidColorBrush(Colors.WhiteSmoke); Icon = UserInterfaceHelpers.GetImageSource("sparkleshare-app", "ico"); TaskbarItemInfo = new TaskbarItemInfo() { Description = "SparkleShare" }; WindowStartupLocation = WindowStartupLocation.CenterScreen; Content = ContentCanvas; // Remove the close button Closing += Close; SourceInitialized += delegate { const int gwl_style = -16; const int ws_sysmenu = 0x00080000; WindowInteropHelper helper = new WindowInteropHelper(this); int style = GetWindowLong(helper.Handle, gwl_style); SetWindowLong(helper.Handle, gwl_style, style & ~ws_sysmenu); }; this.bar = new Rectangle() { Width = Width, Height = 40, Fill = new SolidColorBrush(Color.FromRgb(240, 240, 240)) }; this.line = new Rectangle() { Width = Width, Height = 1, Fill = new SolidColorBrush(Color.FromRgb(223, 223, 223)) }; this.side_splash = new Image() { Width = 150, Height = 482 }; this.side_splash.Source = UserInterfaceHelpers.GetImageSource("side-splash"); ContentCanvas.Children.Add(this.bar); Canvas.SetRight(bar, 0); Canvas.SetBottom(bar, 0); ContentCanvas.Children.Add(this.line); Canvas.SetRight(this.line, 0); Canvas.SetBottom(this.line, 40); ContentCanvas.Children.Add(this.side_splash); Canvas.SetLeft(this.side_splash, 0); Canvas.SetBottom(this.side_splash, 0); }
protected void UpdateWindow() { if (this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip) { this.windowChrome.ResizeBorderThickness = new Thickness(6); } else { this.windowChrome.ResizeBorderThickness = new Thickness(0); } if (this.WindowState == WindowState.Maximized) { var mHwnd = new WindowInteropHelper(this).Handle; var monitor = NativeMethods.MonitorFromWindow(mHwnd, Native.Constants.MONITOR_DEFAULTTONEAREST); var pData = new APPBARDATA(); pData.cbSize = Marshal.SizeOf(pData); pData.hWnd = mHwnd; if (Convert.ToBoolean(NativeMethods.SHAppBarMessage((int)ABMsg.ABM_GETSTATE, ref pData))) { if (monitor != IntPtr.Zero) { var monitorInfo = new MONITORINFO(); NativeMethods.GetMonitorInfo(monitor, monitorInfo); int x = monitorInfo.rcWork.left; int y = monitorInfo.rcWork.top; int cx = monitorInfo.rcWork.right - x; int cy = monitorInfo.rcWork.bottom - y; NativeMethods.SHAppBarMessage((int)ABMsg.ABM_GETTASKBARPOS, ref pData); var uEdge = GetEdge(pData.rc); switch (uEdge) { case ABEdge.ABE_TOP: y++; break; case ABEdge.ABE_BOTTOM: cy--; break; case ABEdge.ABE_LEFT: x++; break; case ABEdge.ABE_RIGHT: cx--; break; } NativeMethods.SetWindowPos(mHwnd, new IntPtr(Native.Constants.HWND_NOTOPMOST), x, y, cx, cy, Native.Constants.SWP_SHOWWINDOW); } } else { this.windowBorder.BorderThickness = new Thickness(6); } this.windowChrome.GlassFrameThickness = new Thickness(0); this.windowChrome.ResizeBorderThickness = new Thickness(0); this.maximizeButton.ToolTip = RestoreToolTip; } else { this.windowChrome.GlassFrameThickness = new Thickness(1, 0, 0, 0); this.windowBorder.BorderThickness = this.previousBorderThickness; this.maximizeButton.ToolTip = MaximizeToolTip; } }
private void HandleConsoleWindowMoves() { var changeTime = DateTimeOffset.UtcNow.Ticks; // If the console is iconic, iconize ourselves. if (User32.IsIconic(_targetWindow)) { WindowState = WindowState.Minimized; Interlocked.Exchange(ref _lastChange, changeTime); return; } if (!User32.GetWindowRect(_targetWindow, out var rect)) { _trace.TraceError("Unable to determine window position."); return; } var interopHelper = new WindowInteropHelper(this); User32.GetWindowRect(interopHelper.Handle, out var ourRect); var windowPlacement = new WINDOWPLACEMENT(); if (!User32.GetWindowPlacement(_targetWindow, ref windowPlacement)) { _trace.TraceError("Unable to determine window placement. Smart-maximization is not supported."); } else if (windowPlacement.showCmd == ShowWindowValue.SW_MAXIMIZE) { _trace.TraceVerbose("Maximization detected; will try to smart-maximize."); User32.ShowWindow(_targetWindow, ShowWindowValue.SW_RESTORE); if (!WaitForRestore(_targetWindow, TimeSpan.FromMilliseconds(500))) { _trace.TraceError("Unable to restore target window; smart-maximize failed."); return; } User32.MoveWindow(_targetWindow, rect.X, rect.Y, rect.Width, rect.Height - ourRect.Height, true); Interlocked.Exchange(ref _lastChange, changeTime); return; } // Otherwise get out of iconic state. if (WindowState != WindowState.Normal) { WindowState = WindowState.Normal; Interlocked.Exchange(ref _lastChange, changeTime); } var newTop = rect.Bottom + 1; if (ourRect.Left != rect.Left || ourRect.Top != newTop || ourRect.Right != rect.Right) { // Using Win32 to move because it works regardless of DPI settings. User32.MoveWindow(interopHelper.Handle, rect.X, newTop, rect.Width, ourRect.Height, true); Interlocked.Exchange(ref _lastChange, changeTime); } // If we are active, we know that the console is not. This is a final state. if (IsActive) { // Allow the user to activate the console without circling back. _activateWithConsole = false; return; } var hwndTop = User32.GetForegroundWindow(); if (hwndTop != _targetWindow) { // The console is not the foreground window. We need to activate ourselves when the console becomes the foreground window. _activateWithConsole = true; // For now there is nothing to do. The focus is on another application. return; } // The console is the foreground window. Check if we need to activate ourselves. if (_activateWithConsole) { Activate(); _activateWithConsole = false; Interlocked.Exchange(ref _lastChange, changeTime); } }
private void Window_Loaded(object sender, RoutedEventArgs e) { var mainWindowPtr = new WindowInteropHelper(this).Handle; var mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr); if (mainWindowSrc != null) { if (mainWindowSrc.CompositionTarget != null) { mainWindowSrc.CompositionTarget.BackgroundColor = System.Windows.Media.Color.FromArgb(0, 0, 0, 0); } } var margins = new NonClientRegionAPI.MARGINS { cxLeftWidth = 0, cxRightWidth = Convert.ToInt32(this.Width) * Convert.ToInt32(this.Width), cyTopHeight = 0, cyBottomHeight = Convert.ToInt32(this.Height) * Convert.ToInt32(this.Height) }; if (mainWindowSrc != null) { NonClientRegionAPI.DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins); } return; //try //{ // // Obtain the window handle for WPF application // IntPtr mainWindowPtr = new WindowInteropHelper(this).Handle; // HwndSource mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr); // mainWindowSrc.CompositionTarget.BackgroundColor = Color.FromArgb(0, 0, 0, 0); // // Get System Dpi // System.Drawing.Graphics desktop = System.Drawing.Graphics.FromHwnd(mainWindowPtr); // float DesktopDpiX = desktop.DpiX; // float DesktopDpiY = desktop.DpiY; // // Set Margins // NonClientRegionAPI.MARGINS margins = new NonClientRegionAPI.MARGINS(); // // Extend glass frame into client area // // Note that the default desktop Dpi is 96dpi. The margins are // // adjusted for the system Dpi. // margins.cxLeftWidth = Convert.ToInt32(5 * (DesktopDpiX / 96)); // margins.cxRightWidth = Convert.ToInt32(5 * (DesktopDpiX / 96)); // margins.cyTopHeight = Convert.ToInt32(5 * (DesktopDpiX / 96)); // margins.cyBottomHeight = Convert.ToInt32(5 * (DesktopDpiX / 96)); // int hr = NonClientRegionAPI.DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins); // // // if (hr < 0) // { // //DwmExtendFrameIntoClientArea Failed // } //} //// If not Vista, paint background white. //catch (DllNotFoundException) //{ // Application.Current.MainWindow.Background = Brushes.White; //} }
private void WindowBase_Loaded(object sender, RoutedEventArgs e) { _interopHelper = new WindowInteropHelper(this); OnLoad(e); }
private static void ShowCloseButton(Window w) { var hwnd = new WindowInteropHelper(w).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_SYSMENU); }
public static void ABSetPos(Window abWindow, double width, double height, ABEdge edge) { NativeMethods.APPBARDATA abd = new NativeMethods.APPBARDATA(); abd.cbSize = Marshal.SizeOf(typeof(NativeMethods.APPBARDATA)); IntPtr handle = new WindowInteropHelper(abWindow).Handle; abd.hWnd = handle; abd.uEdge = (int)edge; int sWidth; int sHeight; // adjust size for dpi Shell.TransformToPixels(width, height, out sWidth, out sHeight); if (abd.uEdge == (int)ABEdge.ABE_LEFT || abd.uEdge == (int)ABEdge.ABE_RIGHT) { abd.rc.top = 0; abd.rc.bottom = SystemInformation.WorkingArea.Bottom; if (abd.uEdge == (int)ABEdge.ABE_LEFT) { abd.rc.left = SystemInformation.WorkingArea.Left; abd.rc.right = abd.rc.left + sWidth; } else { abd.rc.right = SystemInformation.WorkingArea.Right; abd.rc.left = abd.rc.right - sWidth; } } else { abd.rc.left = SystemInformation.WorkingArea.Left; abd.rc.right = SystemInformation.WorkingArea.Right; if (abd.uEdge == (int)ABEdge.ABE_TOP) { if (abWindow is Taskbar) { abd.rc.top = Convert.ToInt32(Startup.MenuBarWindow.Height); } else { abd.rc.top = 0; } abd.rc.bottom = abd.rc.top + sHeight; } else { abd.rc.bottom = SystemInformation.VirtualScreen.Bottom; abd.rc.top = abd.rc.bottom - sHeight; } } NativeMethods.SHAppBarMessage((int)NativeMethods.ABMsg.ABM_QUERYPOS, ref abd); // system doesn't adjust all edges for us, do some adjustments switch (abd.uEdge) { case (int)ABEdge.ABE_LEFT: abd.rc.right = abd.rc.left + sWidth; break; case (int)ABEdge.ABE_RIGHT: abd.rc.left = abd.rc.right - sWidth; break; case (int)ABEdge.ABE_TOP: abd.rc.bottom = abd.rc.top + sHeight; break; case (int)ABEdge.ABE_BOTTOM: abd.rc.top = abd.rc.bottom - sHeight; break; } NativeMethods.SHAppBarMessage((int)NativeMethods.ABMsg.ABM_SETPOS, ref abd); // tracing int h = abd.rc.bottom - abd.rc.top; Trace.WriteLineIf(abd.uEdge == (int)ABEdge.ABE_TOP, "Top AppBar height is " + h.ToString()); Trace.WriteLineIf(abd.uEdge == (int)ABEdge.ABE_BOTTOM, "Bottom AppBar height is " + h.ToString()); abWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ResizeDelegate(DoResize), abd.hWnd, abd.rc.left, abd.rc.top, abd.rc.right - abd.rc.left, abd.rc.bottom - abd.rc.top); if (h < sHeight) { ABSetPos(abWindow, width, height, edge); } }
public static void Initialize(Window window) { DEV_BROADCAST_HDR _data = new DEV_BROADCAST_HDR(); _data.dbch_size = Marshal.SizeOf(_data); _data.dbch_devicetype = DBCH_DEVICETYPE.DBT_DEVTYP_DEVICEINTERFACE; IntPtr _buffer = Marshal.AllocHGlobal(_data.dbch_size); Marshal.StructureToPtr(_data, _buffer, true); IntPtr _hwnd = new WindowInteropHelper(window).Handle; NativeMethods.RegisterDeviceNotification( _hwnd, _buffer, FLAGS.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES ); HwndSource.FromHwnd(_hwnd).AddHook(DeviceHook); }
public static bool FitInScreen(Window window) { var windowInteropHelper = new WindowInteropHelper(window); IntPtr hMonitor = MonitorFromWindow(windowInteropHelper.Handle, MONITOR_DEFAULTTONEAREST); if (hMonitor == IntPtr.Zero) { return(false); } var monitorInfo = MonitorInfoEx.Create(); if (GetMonitorInfo(hMonitor, ref monitorInfo) == false) { return(false); } DpiScale dpiInfo = VisualTreeHelper.GetDpi(App.Current.MainWindow); monitorInfo.Monitor.bottom = (int)Math.Floor(monitorInfo.Monitor.right / dpiInfo.DpiScaleX); monitorInfo.Monitor.bottom = (int)Math.Floor(monitorInfo.Monitor.bottom / dpiInfo.DpiScaleY); monitorInfo.WorkArea.right = (int)Math.Floor(monitorInfo.WorkArea.right / dpiInfo.DpiScaleX); monitorInfo.WorkArea.bottom = (int)Math.Floor(monitorInfo.WorkArea.bottom / dpiInfo.DpiScaleY); int top = (int)window.Top; if (top < monitorInfo.WorkArea.top) { window.Top = monitorInfo.WorkArea.top; } int bottom = (int)(window.Top + window.Height); if (bottom > monitorInfo.WorkArea.bottom) { if (window.Height < monitorInfo.WorkArea.bottom) { window.Top = monitorInfo.WorkArea.bottom - window.Height; } else { window.Top = monitorInfo.WorkArea.top; window.Height = monitorInfo.WorkArea.bottom - monitorInfo.WorkArea.top; } } int left = (int)window.Left; if (left < monitorInfo.WorkArea.left) { window.Left = monitorInfo.WorkArea.left; } int right = (int)(window.Left + window.Width); if (right > monitorInfo.WorkArea.right) { if (window.Width < monitorInfo.WorkArea.right) { window.Left = monitorInfo.WorkArea.right - window.Width; } else { window.Left = monitorInfo.WorkArea.left; window.Width = monitorInfo.WorkArea.right - monitorInfo.WorkArea.left; } } return(true); }
/// <summary> /// Removes a given window's caption /// </summary> /// <param name="win">The window to remove the caption from</param> public static void RemoveWindowCaption(Window win) { var hwnd = new WindowInteropHelper(win).Handle; NativeMethods.SetWindowLongPtr(hwnd, Convert.ToInt32(GWL.STYLE), (IntPtr)(NativeMethods.GetWindowLong(hwnd, Convert.ToInt32(GWL.STYLE)) & ~Convert.ToInt32(WS.SYSMENU))); }
static void HideCloseButton(Window w) { IntPtr hWnd = new WindowInteropHelper(w).Handle; SetWindowLong(hWnd, GWL_STYLE, GetWindowLong(hWnd, GWL_STYLE) & ~WS_SYSMENU); }
protected override Size ArrangeOverride(Size arrangeBounds) { var size = base.ArrangeOverride(arrangeBounds); if (_browserPageImage != null) { var newWidth = (int)size.Width; var newHeight = (int)size.Height; _logger.Debug("BrowserResize. Old H{0}xW{1}; New H{2}xW{3}.", _browserHeight, _browserWidth, newHeight, newWidth); if (newWidth > 0 && newHeight > 0) { if (!_created) { AttachEventHandlers(this); // TODO: ? // Create the bitmap that holds the rendered website bitmap _browserWidth = newWidth; _browserHeight = newHeight; _browserSizeChanged = true; // Find the window that's hosting us Window parentWnd = FindParentOfType <Window>(this); if (parentWnd != null) { IntPtr hParentWnd = new WindowInteropHelper(parentWnd).Handle; var windowInfo = CefWindowInfo.Create(); windowInfo.SetAsWindowless(hParentWnd, AllowsTransparency); var settings = new CefBrowserSettings(); _cefClient = new WpfCefClient(this); // This is the first time the window is being rendered, so create it. CefBrowserHost.CreateBrowser(windowInfo, _cefClient, settings, !string.IsNullOrEmpty(StartUrl) ? StartUrl : "about:blank"); _created = true; } } else { // Only update the bitmap if the size has changed if (_browserPageBitmap == null || (_browserPageBitmap.Width != newWidth || _browserPageBitmap.Height != newHeight)) { _browserWidth = newWidth; _browserHeight = newHeight; _browserSizeChanged = true; // If the window has already been created, just resize it if (_browserHost != null) { _logger.Trace("CefBrowserHost::WasResized to {0}x{1}.", newWidth, newHeight); _browserHost.WasResized(); } } } } } return(size); }
public static IntPtr GetWindowHwnd(Window window) { WindowInteropHelper windowHwnd = new WindowInteropHelper(window); return(windowHwnd.Handle); }
public static void disableActivation(Window window) { WindowInteropHelper helper = new WindowInteropHelper(window); SetWindowLong(helper.Handle, GWL_EXSTYLE, GetWindowLong(helper.Handle, GWL_EXSTYLE) | WS_EX_NOACTIVATE); }
public static IntPtr GetWindowHandle(this Window window) { WindowInteropHelper helper = new WindowInteropHelper(window); return(helper.Handle); }
/// <summary> /// 退出全屏模式 /// 窗口会回到进入全屏模式时保存的状态 /// 退出全屏模式后会重新启用 DWM 过渡动画 /// </summary> public static void EndFullScreen(System.Windows.Window window) { if (window == null) { throw new ArgumentNullException(nameof(window), $"{nameof(window)} 不能为 null"); } //确保在全屏模式并获取之前保存的状态 if (window.GetValue(BeforeFullScreenWindowPlacementProperty) is InteropValues.WINDOWPLACEMENT placement && window.GetValue(BeforeFullScreenWindowStyleProperty) is InteropValues.WindowStyles style) { var hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) { // 句柄为 0 只有两种情况: // 1. 虽然窗口已进入全屏,但窗口已被关闭; // 2. 窗口初始化前,在还没有调用 StartFullScreen 的前提下就调用了此方法。 // 所以,直接 return 就好。 return; } var hwndSource = HwndSource.FromHwnd(hwnd); //去除hook hwndSource.RemoveHook(KeepFullScreenHook); //恢复保存的状态 //不要改变Style里的WS_MAXIMIZE,否则会使窗口变成最大化状态,但是尺寸不对 //也不要设置回Style里的WS_MINIMIZE,否则会导致窗口最小化按钮显示成还原按钮 InteropMethods.SetWindowLong(hwnd, InteropValues.GWL_STYLE, (IntPtr)(style & ~(InteropValues.WindowStyles.WS_MAXIMIZE | InteropValues.WindowStyles.WS_MINIMIZE))); if ((style & InteropValues.WindowStyles.WS_MINIMIZE) != 0) { //如果窗口进入全屏前是最小化的,这里不让窗口恢复到之前的最小化状态,而是到还原的状态。 //大多数情况下,都不期望在退出全屏的时候,恢复到最小化。 placement.showCmd = InteropValues.SW.RESTORE; } if ((style & InteropValues.WindowStyles.WS_MAXIMIZE) != 0) { //提前调用 ShowWindow 使窗口恢复最大化,若通过 SetWindowPlacement 最大化会导致闪烁,只靠其恢复 RestoreBounds. InteropMethods.ShowWindow(hwnd, InteropValues.SW.MAXIMIZE); } InteropMethods.SetWindowPlacement(hwnd, ref placement); if ((style & InteropValues.WindowStyles.WS_MAXIMIZE) == 0) //如果窗口是最大化就不要修改WPF属性,否则会破坏RestoreBounds,且WPF窗口自身在最大化时,不会修改 Left Top Width Height 属性 { if (InteropMethods.GetWindowRect(hwnd, out var rect)) { //不能用 placement 的坐标,placement是工作区坐标,不是屏幕坐标。 //确保窗口的 WPF 属性与 Win32 位置一致 var logicalPos = hwndSource.CompositionTarget.TransformFromDevice.Transform( new Point(rect.Left, rect.Top)); var logicalSize = hwndSource.CompositionTarget.TransformFromDevice.Transform( new Point(rect.Width, rect.Height)); window.Left = logicalPos.X; window.Top = logicalPos.Y; window.Width = logicalSize.X; window.Height = logicalSize.Y; } } //重新启用 DWM 过渡动画 忽略返回值,若DWM关闭不做处理 InteropMethods.DwmSetWindowAttribute(hwnd, InteropValues.DwmWindowAttribute.DWMWA_TRANSITIONS_FORCEDISABLED, 0, sizeof(int)); //删除保存的状态 window.ClearValue(BeforeFullScreenWindowPlacementProperty); window.ClearValue(BeforeFullScreenWindowStyleProperty); } }
#pragma warning restore SA1310 // Field names should not contain underscore public static void SetWindowStyleToolWindow(Window hwnd) { var helper = new WindowInteropHelper(hwnd).Handle; _ = SetWindowLong(helper, GWL_EX_STYLE, (GetWindowLong(helper, GWL_EX_STYLE) | WS_EX_TOOLWINDOW) & ~WS_EX_APPWINDOW); }
public static Image CaptureWindow(Window window) { var interopHelper = new WindowInteropHelper(window); return(CaptureWindow(interopHelper.Handle)); }
private void Window_Loaded(object sender, RoutedEventArgs e) { var hwnd = new WindowInteropHelper(this).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); }
/// <summary> /// disable windows toolbar's control box /// this will also disable system menu with Alt+Space hotkey /// </summary> public static void DisableControlBox(Window win) { var hwnd = new WindowInteropHelper(win).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); }
public static bool? ShowDialog(this Window win, IntPtr handle) { var helper = new WindowInteropHelper(win) { Owner = handle }; return win.ShowDialog(); }
//最大最小化信息 void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam) { // MINMAXINFO structure Win32.MINMAXINFO mmi = (Win32.MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(Win32.MINMAXINFO)); // Get handle for nearest monitor to this window WindowInteropHelper wih = new WindowInteropHelper(this); IntPtr hMonitor = Win32.MonitorFromWindow(wih.Handle, Win32.MONITOR_DEFAULTTONEAREST); // Get monitor info 显示屏 Win32.MONITORINFOEX monitorInfo = new Win32.MONITORINFOEX(); monitorInfo.cbSize = Marshal.SizeOf(monitorInfo); Win32.GetMonitorInfo(new HandleRef(this, hMonitor), monitorInfo); // Convert working area Win32.RECT workingArea = monitorInfo.rcWork; // Set the maximized size of the window //ptMaxSize: 设置窗口最大化时的宽度、高度 //mmi.ptMaxSize.x = (int)dpiIndependentSize.X; //mmi.ptMaxSize.y = (int)dpiIndependentSize.Y; // Set the position of the maximized window mmi.ptMaxPosition.x = workingArea.Left; mmi.ptMaxPosition.y = workingArea.Top; // Get HwndSource HwndSource source = HwndSource.FromHwnd(wih.Handle); if (source == null) { // Should never be null throw new Exception("Cannot get HwndSource instance."); } if (source.CompositionTarget == null) { // Should never be null throw new Exception("Cannot get HwndTarget instance."); } Matrix matrix = source.CompositionTarget.TransformToDevice; Point dpiIndenpendentTrackingSize = matrix.Transform(new Point( this.MinWidth, this.MinHeight )); if (DMFullScreen) { 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; mmi.ptMaxSize.y = workingArea.Bottom; } // Set the minimum tracking size ptMinTrackSize: 设置窗口最小宽度、高度 mmi.ptMinTrackSize.x = (int)dpiIndenpendentTrackingSize.X; mmi.ptMinTrackSize.y = (int)dpiIndenpendentTrackingSize.Y; Marshal.StructureToPtr(mmi, lParam, true); }
private void Window_SourceInitialized_1(object sender, EventArgs e) { var hwnd = new WindowInteropHelper(this).Handle; User32.SetWindowExStyle(hwnd, User32.WsExTransparent | User32.WsExToolWindow); }
public static void Initialize(MainWindow window) { IntPtr handle = new WindowInteropHelper(window).Handle; IsAvailable = false; ContInfoFromLog = LogParser.GetXInputControllerIds(); try { //some users wont even have xinput installed. in order to avoid spurious exceptions and possible instability, check for the library first HasGetInputStateEx = true; LibraryHandle = NativeMethods.LoadLibrary("xinput1_3.dll"); // Win32.LoadLibrary("xinput1_3.dll"); if (LibraryHandle == IntPtr.Zero) { LibraryHandle = NativeMethods.LoadLibrary("xinput1_4.dll"); } if (LibraryHandle == IntPtr.Zero) { LibraryHandle = NativeMethods.LoadLibrary("xinput9_1_0.dll"); HasGetInputStateEx = false; } if (LibraryHandle != IntPtr.Zero) { if (HasGetInputStateEx) { IntPtr proc = GetProcAddressOrdinal(LibraryHandle, new IntPtr(100)); XInputGetStateExProc = (XInputGetStateExProcDelegate)Marshal.GetDelegateForFunctionPointer(proc, typeof(XInputGetStateExProcDelegate)); } //don't remove this code. it's important to catch errors on systems with broken xinput installs. //(probably, checking for the library was adequate, but lets not get rid of this anyway) var test = new SlimDX.XInput.Controller(UserIndex.One).IsConnected; IsAvailable = true; } } catch { } if (!IsAvailable) { return; } //now, at this point, slimdx may be using one xinput, and we may be using another //i'm not sure how slimdx picks its dll to bind to. //i'm not sure how troublesome this will be //maybe we should get rid of slimdx for this altogether var c1 = new Controller(UserIndex.One); var c2 = new Controller(UserIndex.Two); var c3 = new Controller(UserIndex.Three); var c4 = new Controller(UserIndex.Four); if (c1.IsConnected) { Devices.Add(new GamePad360(0, c1, ContInfoFromLog[0])); } if (c2.IsConnected) { Devices.Add(new GamePad360(1, c2, ContInfoFromLog[1])); } if (c3.IsConnected) { Devices.Add(new GamePad360(2, c3, ContInfoFromLog[2])); } if (c4.IsConnected) { Devices.Add(new GamePad360(3, c4, ContInfoFromLog[3])); } }
public HotKey(ModifierKeys modifierKeys, Keys key, WindowInteropHelper window) : this(modifierKeys, key, window.Handle) { Contract.Requires(window != null); }