繁体   English   中英

如何获取表单的位置和显示的屏幕,并在下次显示表单时恢复该位置?

[英]How do I get the position of a form and the screen it is displayed on, and restore that the next time my form is displayed?

我有2个监视器,我需要保存表单位置,它应该在关闭的屏幕上显示。

有人可以建议如何获取屏幕所在的位置,并在窗体加载时在关闭窗体的屏幕上显示它吗?

我保存在注册表中的设置。

最简单的方法是调用GetWindowPlacement函数 这将返回WINDOWPLACEMENT结构 ,该结构包含有关窗口的屏幕坐标的信息。

使用此函数代替Form.Location属性可以解决使用多个监视器,最小化窗口,任务栏位置不正确等问题。

攻击途径是在应用程序关闭时调用GetWindowPlacement函数,将窗口的位置保留在注册表中(或存储窗口的任何位置,注册表不再是保存应用程序状态的推荐位置),并且然后在重新打开应用程序时,调用相应的SetWindowPlacement函数以将窗口还原到其先前位置。

由于这些是Win32 API公开的本机函数,并且您使用的是C#,因此需要通过P / Invoke调用它们。 这是必需的定义(出于组织目的,我建议将它们放在名为NativeMethods的静态类中):

[StructLayout(LayoutKind.Sequential)]
struct POINT
{
    public int X;
    public int Y;
}

[StructLayout(LayoutKind.Sequential)]
struct RECT
{
    public int left;
    public int top;
    public int right;
    public int bottom;
}

[Serializable]
[StructLayout(LayoutKind.Sequential)]
struct WINDOWPLACEMENT
{
     public int length;
     public int flags;
     public int showCmd;
     public POINT ptMinPosition;
     public POINT ptMaxPosition;
     public RECT rcNormalPosition; 
}

[DllImport("user32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);

[DllImport("user32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);

要获取窗口的当前位置(在应用关闭时将执行此操作),请使用以下代码:

WINDOWPLACEMENT wp = new WINDOWPLACEMENT();
wp.length = Marshal.SizeOf(wp);
GetWindowPlacement(MyForm.Handle, ref wp);

回想一下,我提到注册表不再是保持应用程序状态的推荐位置。 由于您是在.NET中进行开发的,因此您可以使用更加强大和通用的选项。 并且由于上面声明的WINDOWPLACEMENT类被标记为[Serializable] ,因此很容易将该信息序列化为应用程序设置 ,然后在下次打开时重新加载它。

我多次实现了类似的功能。 您要做的就是在关闭表单时保存Form.WindowStateForm.SizeForm.Loaction属性,并在打开表单时还原它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM