public static WINDOWPLACEMENT GetWindowPlacement(IntPtr hwnd) { WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.length = Marshal.SizeOf(placement); GetWindowPlacement(hwnd, ref placement); return placement; }
public void load() { Debug.Print("" + ht.Values.Count); foreach (DictionaryEntry de in ht) { try { IntPtr hWnd = (IntPtr)de.Key; if (IsWindowVisible(hWnd) == 0) continue; WINDOWPLACEMENT wp = (WINDOWPLACEMENT)de.Value; SetWindowPlacement(hWnd, ref wp); Debug.Print("" + wp.showCmd); if (wp.showCmd == 1) { WINDOWPLACEMENT wp2 = new WINDOWPLACEMENT(); GetWindowPlacement(hWnd, ref wp2); if (wp2.rcNormalPosition.left == wp.rcNormalPosition.left) { RECT r = wp.rcNormalPosition; MoveWindow(hWnd, r.left, r.top, r.right - r.left, r.bottom - r.top, 1); } } } catch { } } }
public void save() { EnumWindows(new EnumWindowsDelegate(delegate(IntPtr hWnd, int lParam) { StringBuilder sb = new StringBuilder(0x1024); if (IsWindowVisible(hWnd) != 0 && GetWindowText(hWnd, sb, sb.Capacity) != 0) { try { string title = sb.ToString(); int pid; GetWindowThreadProcessId(hWnd, out pid); Process p = Process.GetProcessById(pid); WINDOWPLACEMENT wndpl = new WINDOWPLACEMENT(); wndpl.Length = Marshal.SizeOf(wndpl); GetWindowPlacement(hWnd, ref wndpl); ht[hWnd] = wndpl; } catch { } } return 1; }), 0); }
public static bool GetMinimized() { WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.length = Marshal.SizeOf(placement); GetWindowPlacement(Process.GetCurrentProcess().MainWindowHandle, ref placement); return placement.showCmd == SW_SHOWMINIMIZED; }
public static bool GetVisible() { WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.length = Marshal.SizeOf(placement); GetWindowPlacement(Process.GetCurrentProcess().MainWindowHandle, ref placement); return placement.showCmd != SW_HIDE; }
public static WINDOWPLACEMENT GetWindowPlacement(IntPtr handle) { WINDOWPLACEMENT windowPlacement = new WINDOWPLACEMENT(); if (!GetWindowPlacement(handle, ref windowPlacement)) throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); return windowPlacement; }
//save the placement... private void FormObject_FormClosed(object sender, FormClosedEventArgs e) { //save placement. //all the "tough work" is handled above, and by the INIDataItem Extension methods. Here we //can simply use SetValue<> and set the value. Nice and clean. WINDOWPLACEMENT grabplacement = new WINDOWPLACEMENT(); GetWindowPlacement(FormObject.Handle, ref grabplacement); Configuration[usesectionName][FormObject.Name].SetValue(grabplacement); }
/// <summary> /// Переключается в браузер: /// </summary> private static void ActivateInternet() { //System.Threading.Thread.Sleep(3000); IntPtr handle = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Chrome_WidgetWin_1", null); //IntPtr hide_handle = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Chrome_WidgetWin_1", null); //System.Threading.Thread.Sleep(5000); if (handle != IntPtr.Zero) { //System.Threading.Thread.Sleep(1000); IntPtr current_active = GetForegroundWindow(); handle = FindWindowEx(IntPtr.Zero, handle, "Chrome_WidgetWin_1", null); WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.Length = Marshal.SizeOf(placement); GetWindowPlacement((IntPtr)handle, out placement); if (placement.ShowCmd == 3 || placement.ShowCmd == 1)//maximized || normal { ShowWindow((IntPtr)handle, Constants.SW_MINIMIZE); //UpdateWindow((IntPtr)handle); return; } //if (current_active != handle) else if (placement.ShowCmd == 2)//minimized { //handle = FindWindowEx(IntPtr.Zero, handle, "Chrome_WidgetWin_1", null); ShowWindow((IntPtr)handle, Constants.SW_SHOW); ShowWindow((IntPtr)handle, Constants.SW_MAXIMIZE); UpdateWindow((IntPtr)handle); SetActiveWindow((IntPtr)handle); SetFocus((IntPtr)handle); //SetWindowPos((IntPtr)handle, (IntPtr)Constants.HWND_TOP, 0, 0, 0, 0, Constants.SWP_NOMOVE | Constants.SWP_NOSIZE | Constants.SWP_FRAMECHANGED); SetForegroundWindow(handle); return; } else if (false)//normal { SetForegroundWindow(handle); //handle = FindWindowEx(IntPtr.Zero, handle, "Chrome_WidgetWin_1", null); ShowWindow((IntPtr)handle, Constants.SW_MINIMIZE); //ShowWindow((IntPtr)handle, Constants.SW_HIDE); //ShowWindow((IntPtr)handle, Constants.SW_RESTORE); //UpdateWindow((IntPtr)handle); return; } } else { Process.Start("chrome.exe", "www.yandex.ru"); System.Threading.Thread.Sleep(1000); } //System.Threading.Thread.Sleep(1000); }
public static bool isWindowMinimized(IntPtr hWnd) { WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.length = Marshal.SizeOf(placement); var result = GetWindowPlacement(hWnd, ref placement); if (result) { return placement.showCmd == SW_SHOWMINIMIZED; } throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not get window placement"); }
public static Point GetPlacement(IntPtr handle) { var placement = new WINDOWPLACEMENT(); placement.length = Marshal.SizeOf(placement); if (GetWindowPlacement(handle, ref placement)) { var location = placement.rcNormalPosition; return new Point(location.X + location.Width/2, location.Y + location.Height / 2); } Logger.Write("placement not found."); return new Point(0, 0); }
public static void FocusWindow(IntPtr hwnd) { try { WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.length = Marshal.SizeOf(placement); if (GetWindowPlacement(hwnd, ref placement)) { if (placement.showCmd == ShowCmds.Minimized) NativeMethods.ShowWindow(hwnd, NativeMethods.SW_RESTORE); SetForegroundWindow(hwnd); } } catch { } }
public static void Restore(Window window, XElement xml) { var placement = new WINDOWPLACEMENT(); placement.length = Marshal.SizeOf(typeof(WINDOWPLACEMENT)); placement.flags = 0; placement.showCmd = (int)xml.Element(ShowCommandElementName); placement.ptMinPosition.x = (int)xml.Element(MinPositionElementName).Attribute(XAttributeName); placement.ptMinPosition.y = (int)xml.Element(MinPositionElementName).Attribute(YAttributeName); placement.ptMaxPosition.x = (int)xml.Element(MaxPositionElementName).Attribute(XAttributeName); placement.ptMaxPosition.y = (int)xml.Element(MaxPositionElementName).Attribute(YAttributeName); placement.rcNormalPosition.left = (int)xml.Element(NormalPositionElementName).Attribute(LeftAttributeName); placement.rcNormalPosition.top = (int)xml.Element(NormalPositionElementName).Attribute(TopAttributeName); placement.rcNormalPosition.right = (int)xml.Element(NormalPositionElementName).Attribute(RightAttributeName); placement.rcNormalPosition.bottom = (int)xml.Element(NormalPositionElementName).Attribute(BottomAttributeName); var windowInteropHelper = new WindowInteropHelper(window); SetWindowPlacement(windowInteropHelper.Handle, ref placement); }
public static XElement Save(Window window) { var windowInteropHelper = new WindowInteropHelper(window); var placement = new WINDOWPLACEMENT(); GetWindowPlacement(windowInteropHelper.Handle, out placement); return new XElement(WindowPlacementElementName, new XElement(ShowCommandElementName, (placement.showCmd == SW_SHOWMINIMIZED ? SW_SHOWNORMAL : placement.showCmd)), new XElement(MinPositionElementName, new XAttribute(XAttributeName, placement.ptMinPosition.x), new XAttribute(YAttributeName, placement.ptMinPosition.y)), new XElement(MaxPositionElementName, new XAttribute(XAttributeName, placement.ptMaxPosition.x), new XAttribute(YAttributeName, placement.ptMaxPosition.y)), new XElement(NormalPositionElementName, new XAttribute(LeftAttributeName, placement.rcNormalPosition.left), new XAttribute(TopAttributeName, placement.rcNormalPosition.top), new XAttribute(RightAttributeName, placement.rcNormalPosition.right), new XAttribute(BottomAttributeName, placement.rcNormalPosition.bottom))); }
//Load event: load the form placement, if present, from the INI file we were given in our constructor. private void FormObject_Load(object sender, EventArgs e) { WINDOWPLACEMENT currplacement = new WINDOWPLACEMENT(); GetWindowPlacement(FormObject.Handle, ref currplacement); //default is wherever it is now if there is a parse problem. WINDOWPLACEMENT getplacement = Configuration[usesectionName][FormObject.Name].GetValue(currplacement); //check for previous instances, and offset if there are. String thisproc = Process.GetCurrentProcess().ProcessName; Process[] existing = Process.GetProcessesByName(thisproc); if (existing.Length > 1) { //more than one, so offset... OffsetRect(ref getplacement.rcNormalPosition, 16*existing.Length, 16*existing.Length); } SetWindowPlacement(FormObject.Handle, ref getplacement); //load placement... }
// when we call this function, we must remove the skin from the dictionary void UninitializeActiveWindows( SkinInfo skin ) { Debug.Assert( Dispatcher.CurrentDispatcher == NoFocusManager.ExternalDispatcher, "This method should only be called by the ExternalThread." ); //Setting the config is done after closing the window because modifying a value in the Config //Triggers a Caliburn Micro OnNotifyPropertyChanged, which calls an Invoke on the main UI Thread. //generating random locks. //Once the LayoutManager is ready, we won't need this anymore. WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); UnregisterSkinEvents( skin ); Unsubscribe( skin ); UnregisterFromHighlighter( skin ); UnregisterTopMostService( skin ); placement = CKWindowTools.GetPlacement( skin.Skin.Hwnd ); skin.ViewModel.Dispose(); if( _skins.Count == 1 && _miniView != null && _miniView.Visibility != Visibility.Hidden ) { if( Highlighter.Status.IsStartingOrStarted ) Highlighter.Service.UnregisterTree( _miniViewVm.Name, _miniViewVm ); _miniView.Hide(); _viewHidden = false; } //temporary 03/03/2014 if( !skin.IsClosing ) { skin.IsClosing = true; skin.Skin.Dispatcher.Invoke( (Action)(() => { skin.Skin.Close(); }) ); } Config.User.Set( PlacementString( skin ), placement ); }
/// <summary> /// Activates the window by handle. /// </summary> /// <param name="hWnd">The handle to the window to activate.</param> public static void ActivateWindowByHandle(IntPtr hWnd) { WINDOWPLACEMENT windowPlacement = new WINDOWPLACEMENT(); windowPlacement.length = Marshal.SizeOf(windowPlacement); GetWindowPlacement(hWnd, ref windowPlacement); switch (windowPlacement.showCmd) { case WindowShowStyle.Hide: ShowWindow(hWnd, WindowShowStyle.Restore); break; case WindowShowStyle.ShowMinimized: if (windowPlacement.flags == WPF_RESTORETOMAXIMIZED) ShowWindow(hWnd, WindowShowStyle.ShowMaximized); else ShowWindow(hWnd, WindowShowStyle.ShowNormal); break; default: SetForegroundWindow(hWnd, true); break; } }
public static WindowStateData getAppropriateViewData() { var window = currentWindow(); // var stateData = new WindowStateData(); var placementData = new WINDOWPLACEMENT(); GetWindowPlacement(window, out placementData); stateData.isVisible = (isWindowFocused(window) || (ThisAddIn.instance != null && ThisAddIn.instance.SSSW != null && ThisAddIn.instance.SSSW.HWND != null && isWindowFocused(ThisAddIn.instance.SSSW.HWND))); RECT rect = new RECT(); if (placementData.showCmd != SW_SHOWMAXIMIZED) { GetWindowRect((int)window, ref rect); stateData.X = rect.left; stateData.Y = rect.top; stateData.Height = rect.bottom - rect.top; } else { stateData.X = 0; stateData.Y = 0; stateData.Height = System.Windows.Forms.Screen.FromHandle(window).WorkingArea.Height; } return stateData; }
public static extern bool SetWindowPlacement(HandleRef hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
private static extern BOOL GetWindowPlacementInternal(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
/// <summary> /// Creates and populates the MINMAXINFO structure for a maximized window. /// Puts the structure into memory address given by lParam. /// Only used to process a WM_GETMINMAXINFO message. /// </summary> /// <param name="hwnd">The window handle.</param> /// <param name="lParam">The lParam.</param> private void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam) { var structure = (NativeMethods.MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(NativeMethods.MINMAXINFO)); // var monitor = new Monitor(_handle); // monitor.Invalidate(); // Taskbar.Invalidate(); object monitor = this.monitorConstructor.Invoke(new object[] { this.handle }); this.monitorInvalidateMethod.Invoke(monitor, new object[] { }); this.taskbarInvalidateMethod.Invoke(null, new object[] { }); // var bounds = monitor.Bounds; // var workArea = monitor.WorkArea; object bounds = this.monitorBoundsProperty.GetValue(monitor); object workArea = this.monitorWorkAreaProperty.GetValue(monitor); if (this.boundsLeftField == null) { Type boundsType = bounds.GetType(); this.boundsLeftField = boundsType.GetField("left", this.bindingFlags); this.boundsTopField = boundsType.GetField("top", this.bindingFlags); Type workAreaType = workArea.GetType(); this.workAreaTopField = workAreaType.GetField("top", this.bindingFlags); this.workAreaBottomField = workAreaType.GetField("bottom", this.bindingFlags); } int boundsLeft = (int)this.boundsLeftField.GetValue(bounds); int boundsTop = (int)this.boundsTopField.GetValue(bounds); int workAreaLeft; int workAreaRight; WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); NativeMethods.GetWindowPlacement(this.handle, out placement); //placement.showCmd == ShowWindowCommands if (placement.showCmd == 3) { workAreaLeft = (int)workArea.GetType().GetField("left", bindingFlags).GetValue(workArea); workAreaRight = (int)workArea.GetType().GetField("right", bindingFlags).GetValue(workArea); } else { // Allow the screen to be resized accross multiple monitors. // This does not work when the user double clicks the title bar as the WindowState shows as Normal. workAreaLeft = 0; workAreaRight = (int)SystemParameters.VirtualScreenWidth; } int workAreaTop = (int)this.workAreaTopField.GetValue(workArea); int workAreaBottom = (int)this.workAreaBottomField.GetValue(workArea); int taskbarPosition = (int)this.taskbarPositionProperty.GetValue(null); bool taskbarAutoHide = (bool)this.taskbarAutoHideProperty.GetValue(null); structure.MaxPosition.X = Math.Abs(boundsLeft) + taskbarPosition == 0 && taskbarAutoHide ? 1 : 0; structure.MaxPosition.Y = Math.Abs(boundsTop) + taskbarPosition == 1 && taskbarAutoHide ? 1 : 0; // WARNING: MAGIC NUMBER - Why Do I Need to take away 3!!! structure.MaxSize.X = structure.MaxTrackSize.X = Math.Abs(workAreaRight - workAreaLeft) - (taskbarPosition == 2 && taskbarAutoHide ? 1 : 0) - 3; structure.MaxSize.Y = structure.MaxTrackSize.Y = Math.Abs(workAreaBottom - workAreaTop) - (taskbarPosition == 3 && taskbarAutoHide ? 1 : 0); var source = PresentationSource.FromVisual(this); if (source != null && source.CompositionTarget != null) { if (IsNonNegative(MinWidth)) { structure.MinTrackSize.X = (int)Math.Ceiling(MinWidth * source.CompositionTarget.TransformFromDevice.M11); } if (IsNonNegative(MinHeight)) { structure.MinTrackSize.Y = (int)Math.Ceiling(MinHeight * source.CompositionTarget.TransformFromDevice.M22); } if (IsNonNegative(MaxWidth)) { structure.MaxSize.X = structure.MaxTrackSize.X = Math.Min(structure.MaxSize.X, (int)Math.Ceiling(MaxWidth * source.CompositionTarget.TransformFromDevice.M11)); } if (IsNonNegative(MaxHeight)) { structure.MaxSize.Y = structure.MaxTrackSize.Y = Math.Min(structure.MaxSize.Y, (int)Math.Ceiling(MaxHeight * source.CompositionTarget.TransformFromDevice.M22)); } } Marshal.StructureToPtr(structure, lParam, true); }
public static extern bool GetWindowPlacement(HandleRef hWnd, out WINDOWPLACEMENT lpwndpl);
/** * <summary> * Retrieves the show state and the restored, minimized, and maximized positions of the specified window. * </summary> * <param name="hwnd">A handle to the window. </param> * <param name="lpwndpl">A pointer to the WINDOWPLACEMENT structure that receives the show state and position information.</param> * <returns>If the function succeeds, the return value is nonzero.</returns> * <remarks></remarks> */ /** \remark Is imported from external library: user32 */ private extern int GetWindowPlacement(IntPtr hwnd, ref WINDOWPLACEMENT lpwndpl);
private void _SetRoundingRegion(WINDOWPOS?wp) { WINDOWPLACEMENT windowPlacement = NativeMethods.GetWindowPlacement(this._hwnd); if (windowPlacement.showCmd == SW.SHOWMAXIMIZED) { int num; int num2; if (wp != null) { num = wp.Value.x; num2 = wp.Value.y; } else { Rect rect = this._GetWindowRect(); num = (int)rect.Left; num2 = (int)rect.Top; } IntPtr hMonitor = NativeMethods.MonitorFromWindow(this._hwnd, 2U); MONITORINFO monitorInfo = NativeMethods.GetMonitorInfo(hMonitor); RECT rcWork = monitorInfo.rcWork; rcWork.Offset(-num, -num2); IntPtr hRgn = IntPtr.Zero; try { hRgn = NativeMethods.CreateRectRgnIndirect(rcWork); NativeMethods.SetWindowRgn(this._hwnd, hRgn, NativeMethods.IsWindowVisible(this._hwnd)); hRgn = IntPtr.Zero; return; } finally { Utility.SafeDeleteObject(ref hRgn); } } Size size; if (wp != null && !Utility.IsFlagSet(wp.Value.flags, 1)) { size = new Size((double)wp.Value.cx, (double)wp.Value.cy); } else { if (wp != null && this._lastRoundingState == this._window.WindowState) { return; } size = this._GetWindowRect().Size; } this._lastRoundingState = this._window.WindowState; IntPtr intPtr = IntPtr.Zero; try { DpiScale dpi = this._window.GetDpi(); double num3 = Math.Min(size.Width, size.Height); double num4 = DpiHelper.LogicalPixelsToDevice(new Point(this._chromeInfo.CornerRadius.TopLeft, 0.0), dpi.DpiScaleX, dpi.DpiScaleY).X; num4 = Math.Min(num4, num3 / 2.0); if (WindowChromeWorker._IsUniform(this._chromeInfo.CornerRadius)) { intPtr = WindowChromeWorker._CreateRoundRectRgn(new Rect(size), num4); } else { intPtr = WindowChromeWorker._CreateRoundRectRgn(new Rect(0.0, 0.0, size.Width / 2.0 + num4, size.Height / 2.0 + num4), num4); double num5 = DpiHelper.LogicalPixelsToDevice(new Point(this._chromeInfo.CornerRadius.TopRight, 0.0), dpi.DpiScaleX, dpi.DpiScaleY).X; num5 = Math.Min(num5, num3 / 2.0); Rect region = new Rect(0.0, 0.0, size.Width / 2.0 + num5, size.Height / 2.0 + num5); region.Offset(size.Width / 2.0 - num5, 0.0); WindowChromeWorker._CreateAndCombineRoundRectRgn(intPtr, region, num5); double num6 = DpiHelper.LogicalPixelsToDevice(new Point(this._chromeInfo.CornerRadius.BottomLeft, 0.0), dpi.DpiScaleX, dpi.DpiScaleY).X; num6 = Math.Min(num6, num3 / 2.0); Rect region2 = new Rect(0.0, 0.0, size.Width / 2.0 + num6, size.Height / 2.0 + num6); region2.Offset(0.0, size.Height / 2.0 - num6); WindowChromeWorker._CreateAndCombineRoundRectRgn(intPtr, region2, num6); double num7 = DpiHelper.LogicalPixelsToDevice(new Point(this._chromeInfo.CornerRadius.BottomRight, 0.0), dpi.DpiScaleX, dpi.DpiScaleY).X; num7 = Math.Min(num7, num3 / 2.0); Rect region3 = new Rect(0.0, 0.0, size.Width / 2.0 + num7, size.Height / 2.0 + num7); region3.Offset(size.Width / 2.0 - num7, size.Height / 2.0 - num7); WindowChromeWorker._CreateAndCombineRoundRectRgn(intPtr, region3, num7); } NativeMethods.SetWindowRgn(this._hwnd, intPtr, NativeMethods.IsWindowVisible(this._hwnd)); intPtr = IntPtr.Zero; } finally { Utility.SafeDeleteObject(ref intPtr); } }
private static extern bool SetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
public static extern int GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
/// <summary> /// 指定されたフォームへウィンドウ位置に関する情報を設定する。 /// </summary> /// <param name="form">位置情報の設定先フォーム。</param> /// <param name="fixedSize">フォームのサイズを変更したくないときは true を指定します。</param> public void SetPlacementTo(Form form, bool fixedSize) { if (this.Width <= 0 || this.Height <= 0) { // 幅と高さが0未満の場合は設定しない return; } WINDOWPLACEMENT wndpl = new WINDOWPLACEMENT(); wndpl.length = Marshal.SizeOf(wndpl); wndpl.flags = 0; wndpl.rcNormalPosition.left = this.Left; wndpl.rcNormalPosition.top = this.Top; wndpl.rcNormalPosition.right = this.Left + this.Width; wndpl.rcNormalPosition.bottom = this.Top + this.Height; wndpl.ptMinPosition.x = this.MinX; wndpl.ptMinPosition.y = this.MinY; wndpl.ptMaxPosition.x = this.MaxX; wndpl.ptMaxPosition.y = this.MaxY; switch (this.WindowState) { case FormWindowState.Maximized: wndpl.showCmd = SW_SHOWMAXIMIZED; break; default: wndpl.showCmd = SW_SHOWNORMAL; break; } // 位置がディスプレイの外だとまずいので位置を補正する IntPtr hMonitor = MonitorFromRect(ref wndpl.rcNormalPosition, MONITOR_DEFAULTTONEAREST); MONITORINFO mi = new MONITORINFO(); mi.cbSize = Marshal.SizeOf(mi); GetMonitorInfoW(hMonitor, ref mi); if (wndpl.rcNormalPosition.right > mi.rcMonitor.right) { wndpl.rcNormalPosition.left -= wndpl.rcNormalPosition.right - mi.rcMonitor.right; wndpl.rcNormalPosition.right = mi.rcMonitor.right; } if (wndpl.rcNormalPosition.left < mi.rcMonitor.left) { wndpl.rcNormalPosition.right += mi.rcMonitor.left - wndpl.rcNormalPosition.left; wndpl.rcNormalPosition.left = mi.rcMonitor.left; } if (wndpl.rcNormalPosition.bottom > mi.rcMonitor.bottom) { wndpl.rcNormalPosition.top -= wndpl.rcNormalPosition.bottom - mi.rcMonitor.bottom; wndpl.rcNormalPosition.bottom = mi.rcMonitor.bottom; } if (wndpl.rcNormalPosition.top < mi.rcMonitor.top) { wndpl.rcNormalPosition.bottom += mi.rcMonitor.top - wndpl.rcNormalPosition.top; wndpl.rcNormalPosition.top = mi.rcMonitor.top; } // サイズを固定にしたい場合はサイズが変わらないようにする if (fixedSize) { WINDOWPLACEMENT t = new WINDOWPLACEMENT(); t.length = Marshal.SizeOf(t); GetWindowPlacement(form.Handle, ref t); wndpl.rcNormalPosition.right = wndpl.rcNormalPosition.left + (t.rcNormalPosition.right - t.rcNormalPosition.left); wndpl.rcNormalPosition.bottom = wndpl.rcNormalPosition.top + (t.rcNormalPosition.bottom - t.rcNormalPosition.top); } SetWindowPlacement(form.Handle, ref wndpl); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: winLayout [save | restore]"); return; } Dictionary <string, WINDOWPLACEMENT> winLayouts = new Dictionary <string, WINDOWPLACEMENT>(); string folderName = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData), "WinLayout"); if (!Directory.Exists(folderName)) { Directory.CreateDirectory(folderName); } string configFileName = Path.Combine(folderName, "winlayout.json"); var processes = Process.GetProcesses(); if (string.Equals(args[0], "save", StringComparison.OrdinalIgnoreCase)) { foreach (var process in processes) { var name = process.ProcessName; var windowHandle = process.MainWindowHandle; if (windowHandle == (IntPtr)0) { continue; } WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.length = Marshal.SizeOf(placement); GetWindowPlacement(windowHandle, ref placement); winLayouts[process.ProcessName] = placement; } var placementJson = JsonConvert.SerializeObject(winLayouts); File.WriteAllText(configFileName, placementJson); } else if (string.Equals(args[0], "restore", StringComparison.OrdinalIgnoreCase)) { var plJson = File.ReadAllText(configFileName); var pl = JsonConvert.DeserializeObject <Dictionary <string, WINDOWPLACEMENT> >(plJson); foreach (var procName in pl.Keys) { var procs = processes.Where(p => p.ProcessName == procName); foreach (var proc in procs) { if (proc == null) { continue; } var windowHandle = proc.MainWindowHandle; if (windowHandle == (IntPtr)0) { continue; } // When doing dock/undock, the windowplacement is not recognized as changed // so force a small change by deactivating the windows var winPlacement2 = pl[proc.ProcessName]; winPlacement2.showCmd = 1; SetWindowPlacement(windowHandle, ref winPlacement2); var winPlacement = pl[proc.ProcessName]; SetWindowPlacement(windowHandle, ref winPlacement); break; } } } else { Console.WriteLine("Usage: winLayout [save | restore]"); } }
public static WINDOWPLACEMENT New() { WINDOWPLACEMENT ret = new WINDOWPLACEMENT(); ret.length = (uint)System.Runtime.InteropServices.Marshal.SizeOf(ret); return ret; }
private static WINDOWPLACEMENT GetPlacement(this IntPtr hwnd) { var placement = new WINDOWPLACEMENT(); placement.length = Marshal.SizeOf(placement); GetWindowPlacement(hwnd, ref placement); return placement; }
static void Main(string[] args) { hostname = ConfigurationManager.AppSettings["hostname"]; port = int.Parse(ConfigurationManager.AppSettings["port"]); GetHosts = new List <GameServer>(); PostHosts = new List <GameServer>(); for (int i = 1; ; i++) { try { string host = ConfigurationManager.AppSettings[$"GetHost{i}"]; string port = ConfigurationManager.AppSettings[$"GetPort{i}"]; string timeout = ConfigurationManager.AppSettings[$"GetTimeout{i}"]; if (string.IsNullOrEmpty(host)) { break; } GetHosts.Add(new GameServer() { host = host, port = int.Parse(port), timeout = int.Parse(timeout) }); } catch { break; } } for (int i = 1; ; i++) { try { string host = ConfigurationManager.AppSettings[$"PostHost{i}"]; string port = ConfigurationManager.AppSettings[$"PostPort{i}"]; string timeout = ConfigurationManager.AppSettings[$"PostTimeout{i}"]; if (string.IsNullOrEmpty(host)) { break; } PostHosts.Add(new GameServer() { host = host, port = int.Parse(port), timeout = int.Parse(timeout) }); } catch { break; } } Console.Title = "Raknet Proxy"; // Get The Console Window Handle Me = GetConsoleWindow(); // Disable Close Button (X) EnableMenuItem(GetSystemMenu(Me, false), SC_CLOSE, (uint)(MF_ENABLED | MF_DISABLED)); MenuItem mExit = new MenuItem("Exit", new EventHandler(Exit)); ContextMenu Menu = new ContextMenu(new MenuItem[] { mExit }); Tray = new NotifyIcon() { Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location), Visible = true, Text = Console.Title, ContextMenu = Menu }; Tray.DoubleClick += new EventHandler(DoubleClick); // Detect When The Console Window is Minimized and Hide it Task.Factory.StartNew(() => { for (;;) { WINDOWPLACEMENT wPlacement = new WINDOWPLACEMENT(); GetWindowPlacement(Me, ref wPlacement); if (wPlacement.showCmd == (int)ShowWindowCommands.ShowMinimized) { ShowWindow(Me, (int)ShowWindowCommands.Hide); } // 1 ms Delay to Avoid High CPU Usage //Wait(1); Thread.Sleep(100); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); Task.Factory.StartNew(() => { using (HttpListener listener = new HttpListener()) { listener.Prefixes.Add($"http://{hostname}:{port}/"); listener.Start(); for (;;) { var context = listener.GetContext(); switch (context.Request.HttpMethod) { case "GET": GetGames(context); break; case "POST": case "PUT": PostGame(context, context.Request.HttpMethod); break; case "DELETE": DeleteGame(context); break; default: Console.WriteLine("Unknown HTTP Method"); context.Response.Headers.Add("Allow", "GET, POST, PUT, DELETE"); context.Response.StatusCode = 405; //context.Response.ContentLength64 = 1; //context.Response.OutputStream.WriteByte(0x00); context.Response.OutputStream.Close(); break; } } } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); Console.CancelKeyPress += Console_CancelKeyPress; Application.Run(); }
/// <summary> /// Retrieves the show state and the restored, minimized, and maximized positions of the specified window. /// </summary> /// <param name="hwnd">A handle to the window.</param> /// <param name="placement">The WINDOWPLACEMENT structure that receives the show state and position information. Before calling GetWindowPlacement, set the length member to sizeof(WINDOWPLACEMENT).</param> /// <returns></returns> public static bool GetWindowPlacement(IntPtr hwnd, ref WINDOWPLACEMENT placement) { return(NativeMethods.GetWindowPlacement(hwnd, ref placement)); }
public static extern bool GetWindowPlacement ( [In] this IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl );
/// <summary> /// Set the target's placement. /// </summary> /// <param name="Minimized">true if want to Minimized</param> /// <param name="Maximized">true if want to Maximized</param> /// <param name="hwnd">the target window</param> private static void SetWindowLocation(string position, IntPtr hwnd) { if (hwnd != IntPtr.Zero) { // Prepare the WINDOWPLACEMENT structure. WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.Length = Marshal.SizeOf(placement); // Get the window's current placement. GetWindowPlacement(hwnd, out placement); placement.ShowCmd = ShowWindowCommands.Normal; switch (position.ToLower()) { case "min": placement.ShowCmd = ShowWindowCommands.ShowMinimized; break; case "max": placement.ShowCmd = ShowWindowCommands.ShowMaximized; break; case "normal": break; case "l": placement.NormalPosition._Left = 0; placement.NormalPosition._Right = Screen.PrimaryScreen.WorkingArea.Width / 2; placement.NormalPosition._Top = 0; placement.NormalPosition._Bottom = Screen.PrimaryScreen.WorkingArea.Height; break; case "r": placement.NormalPosition._Left = Screen.PrimaryScreen.WorkingArea.Width / 2; placement.NormalPosition._Right = Screen.PrimaryScreen.WorkingArea.Width; placement.NormalPosition._Top = 0; placement.NormalPosition._Bottom = Screen.PrimaryScreen.WorkingArea.Height; break; case "t": placement.NormalPosition._Left = 0; placement.NormalPosition._Right = Screen.PrimaryScreen.WorkingArea.Width; placement.NormalPosition._Top = 0; placement.NormalPosition._Bottom = Screen.PrimaryScreen.WorkingArea.Height / 2; break; case "b": placement.NormalPosition._Left = 0; placement.NormalPosition._Right = Screen.PrimaryScreen.WorkingArea.Width; placement.NormalPosition._Top = Screen.PrimaryScreen.WorkingArea.Height / 2; placement.NormalPosition._Bottom = Screen.PrimaryScreen.WorkingArea.Height; break; case "tl": placement.NormalPosition._Left = 0; placement.NormalPosition._Right = Screen.PrimaryScreen.WorkingArea.Width / 2; placement.NormalPosition._Top = 0; placement.NormalPosition._Bottom = Screen.PrimaryScreen.WorkingArea.Height / 2; break; case "bl": placement.NormalPosition._Left = 0; placement.NormalPosition._Right = Screen.PrimaryScreen.WorkingArea.Width / 2; placement.NormalPosition._Top = Screen.PrimaryScreen.WorkingArea.Height / 2; placement.NormalPosition._Bottom = Screen.PrimaryScreen.WorkingArea.Height; break; case "tr": placement.NormalPosition._Left = Screen.PrimaryScreen.WorkingArea.Width / 2; placement.NormalPosition._Right = Screen.PrimaryScreen.WorkingArea.Width; placement.NormalPosition._Top = 0; placement.NormalPosition._Bottom = Screen.PrimaryScreen.WorkingArea.Height / 2; break; case "br": placement.NormalPosition._Left = Screen.PrimaryScreen.WorkingArea.Width / 2; placement.NormalPosition._Right = Screen.PrimaryScreen.WorkingArea.Width; placement.NormalPosition._Top = Screen.PrimaryScreen.WorkingArea.Height / 2; placement.NormalPosition._Bottom = Screen.PrimaryScreen.WorkingArea.Height; break; default: break; } // Perform the action. SetWindowPlacement(hwnd, ref placement); } }
public static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);
public static extern bool SetWindowPlacement(HWND hWnd, WINDOWPLACEMENT wndpl);
internal static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
/// <summary> /// Minimize/restore the main window. /// </summary> public static void ToggleWindowState() { var hwnd = getSpotifyHandle(); if (hwnd == IntPtr.Zero) return; var placement = new WINDOWPLACEMENT(); GetWindowPlacement(hwnd, ref placement); if (placement.showCmd == SW_SHOWMINIMIZED) { ShowWindow(hwnd, SW_RESTORE); SetForegroundWindow(hwnd); SetFocus(hwnd); } else { ShowWindow(hwnd, SW_SHOWMINIMIZED); } }
public static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
private WINDOWPLACEMENT GetFormPlacement(Form Src) { WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.length = (uint)Marshal.SizeOf(placement); bool res = GetWindowPlacement(Src.Handle, ref placement); return placement; }
public override void Initialize() { RawData = new WINDOWPLACEMENT(); RawData.length = Marshal.SizeOf(RawData); RawData.flags = 0; }
private void SetWindowPlacement( SkinInfo skinInfo ) { Debug.Assert( Dispatcher.CurrentDispatcher == NoFocusManager.ExternalDispatcher, "This method should only be called by the ExternalThread." ); var defaultPlacement = new WINDOWPLACEMENT(); defaultPlacement = CKWindowTools.GetPlacement( skinInfo.Skin.Hwnd ); WINDOWPLACEMENT actualPlacement = Config.User.GetOrSet( PlacementString( skinInfo ), defaultPlacement ); skinInfo.Dispatcher.Invoke( (Action)(() => CKWindowTools.SetPlacement( skinInfo.Skin.Hwnd, actualPlacement )), null ); }
public Container(WINDOWPLACEMENT placement, DpiScale dpi) { this.Placement = placement; this._dpi = new Point(dpi.DpiScaleX, dpi.DpiScaleY); }
public static extern bool GetWindowPlacement(IntPtr hwnd, out WINDOWPLACEMENT wndpl);
private void ManageExtPlayer(Process player, PlayableItem playable) { //minimize MCE if indicated IntPtr mceWnd = FindWindow(null, "Windows Media Center"); WINDOWPLACEMENT wp = new WINDOWPLACEMENT(); GetWindowPlacement(mceWnd, ref wp); Cursor.Hide(); if (HideTaskbar) { Taskbar.Hide(); } if (ShowSplashScreen) { //throw up a form to cover the desktop if we minimize and we are in the primary monitor if (System.Windows.Forms.Screen.FromHandle(mceWnd).Primary) { ExternalSplashForm.Display(Application.CurrentInstance.ExtSplashBmp); } } if (MinimizeMCE) { Logger.ReportVerbose("Minimizing Windows Media Center"); wp.showCmd = 2; // 1 - Normal; 2 - Minimize; 3 - Maximize; SetWindowPlacement(mceWnd, ref wp); } // async this so it doesn't slow us down if the service isn't responding for some reason Async.Queue("Wait for external player to launch", () => { player.Refresh(); player.WaitForInputIdle(5000); OnExternalPlayerLaunched(playable); }); //and wait for it to exit player.WaitForExit(); player.Dispose(); //now restore MCE wp.showCmd = 1; // 1 - Normal; 2 - Minimize; 3 - Maximize; SetWindowPlacement(mceWnd, ref wp); if (ShowSplashScreen) { ExternalSplashForm.Hide(); } if (HideTaskbar) { Taskbar.Show(); } Cursor.Show(); SetForegroundWindow(mceWnd); OnPlaybackFinished(GetFinishedPlaybackState()); }
public static extern unsafe bool GetWindowPlacement(IntPtr hWnd, WINDOWPLACEMENT* lpwndpl);
internal static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);
private static extern bool GetWindowPlacement( IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
private static extern int _GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT windowPlacement);
public override void Initialize() { RawData = new WINDOWPLACEMENT(); RawData.length = Marshal.SizeOf( RawData ); RawData.flags = 0; }
public static extern bool GetWindowPlacement(IntPtr hwnd, ref WINDOWPLACEMENT placement);
public static extern bool SetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
private void ManageExtPlayer(Process player, PlayableItem playable) { //minimize MCE if indicated IntPtr mceWnd = FindWindow(null, "Windows Media Center"); WINDOWPLACEMENT wp = new WINDOWPLACEMENT(); GetWindowPlacement(mceWnd, ref wp); Cursor.Hide(); if (HideTaskbar) { Taskbar.Hide(); } if (ShowSplashScreen) { //throw up a form to cover the desktop if we minimize and we are in the primary monitor if (System.Windows.Forms.Screen.FromHandle(mceWnd).Primary) { ExternalSplashForm.Display(Application.CurrentInstance.ExtSplashBmp); } } if (MinimizeMCE) { Logger.ReportVerbose("Minimizing Windows Media Center"); wp.showCmd = 2; // 1 - Normal; 2 - Minimize; 3 - Maximize; SetWindowPlacement(mceWnd, ref wp); } // async this so it doesn't slow us down if the service isn't responding for some reason Async.Queue(Async.ThreadPoolName.WaitForExternalPlayerToLaunch, () => { player.Refresh(); player.WaitForInputIdle(5000); OnExternalPlayerLaunched(playable); }); //and wait for it to exit player.WaitForExit(); player.Dispose(); //now restore MCE wp.showCmd = 1; // 1 - Normal; 2 - Minimize; 3 - Maximize; SetWindowPlacement(mceWnd, ref wp); if (ShowSplashScreen) { ExternalSplashForm.Hide(); } if (HideTaskbar) { Taskbar.Show(); } Cursor.Show(); SetForegroundWindow(mceWnd); OnPlaybackFinished(GetFinishedPlaybackState()); }
/// <summary> /// Resizes the window to the requested aspect ratio /// </summary> /// <param name="ratio"></param> public void ResizeWindow(int ratio) { bool validResize = false; //Get the window's placement to tell if maximized or minimized WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); GetWindowPlacement(flashplayerHandle, ref placement); //If not minizimed or maximized validResize = placement.showCmd.Equals(1); if (validResize) { float idealWidth = 0; //4:3 if (ratio == 0) { idealWidth = flashplayerRect.Height * (4f / 3f); if (idealWidth < 300) { idealWidth = 300; flashplayerRect.Height = (int)(idealWidth * (3f / 4f)); flashplayerRect.Y -= 2; flashplayerRect.X -= 9; } } //16:9 if (ratio == 1) { idealWidth = flashplayerRect.Height * (16f / 9f); if (idealWidth < 300) { idealWidth = 300; flashplayerRect.Height = (int)(idealWidth * (9f / 16f)); flashplayerRect.Y -= 2; flashplayerRect.X -= 9; } } //1:1 if (ratio == 2) { idealWidth = flashplayerRect.Height * (1f / 1f); if (idealWidth < 300) { idealWidth = 300; flashplayerRect.Height = 300; flashplayerRect.Y -= 2; flashplayerRect.X -= 9; } } if (Math.Abs(idealWidth - flashplayerRect.Width) > 10) { idealWidth += 4; MoveWindow(flashplayerHandle, flashplayerRect.X, flashplayerRect.Y, (int)idealWidth, flashplayerRect.Height + 50, true); flashplayerRect.Width = (int)idealWidth; } } }
private void _SetRoundingRegion(WINDOWPOS?wp) { const int MONITOR_DEFAULTTONEAREST = 0x00000002; // We're early - WPF hasn't necessarily updated the state of the window. // Need to query it ourselves. WINDOWPLACEMENT wpl = NativeMethods.GetWindowPlacement(_hwnd); if (wpl.showCmd == SW.SHOWMAXIMIZED) { int left; int top; if (wp.HasValue) { left = wp.Value.x; top = wp.Value.y; } else { Rect r = _GetWindowRect(); left = (int)r.Left; top = (int)r.Top; } IntPtr hMon = NativeMethods.MonitorFromWindow(_hwnd, MONITOR_DEFAULTTONEAREST); MONITORINFO mi = NativeMethods.GetMonitorInfo(hMon); RECT rcMax = mi.rcWork; // The location of maximized window takes into account the border that Windows was // going to remove, so we also need to consider it. rcMax.Offset(-left, -top); IntPtr hrgn = NativeMethods.CreateRectRgnIndirect(rcMax); NativeMethods.SetWindowRgn(_hwnd, hrgn, NativeMethods.IsWindowVisible(_hwnd)); } else { int width; int height; // Use the size if it's specified. if (null != wp && !Utility.IsFlagSet(wp.Value.flags, (int)SWP.NOSIZE)) { width = wp.Value.cx; height = wp.Value.cy; } else if (null != wp && (_lastRoundingState == _window.WindowState)) { return; } else { Rect r = _GetWindowRect(); width = (int)r.Width; height = (int)r.Height; } _lastRoundingState = _window.WindowState; IntPtr hrgn = IntPtr.Zero; if (RoundCorners && 0 != RoundCornersRadius) { Point radius = DpiHelper.LogicalPixelsToDevice(new Point(RoundCornersRadius, RoundCornersRadius)); hrgn = NativeMethods.CreateRoundRectRgn(0, 0, width, height, (int)radius.X, (int)radius.Y); } else { hrgn = NativeMethods.CreateRectRgn(0, 0, width, height); } NativeMethods.SetWindowRgn(_hwnd, hrgn, NativeMethods.IsWindowVisible(_hwnd)); } }