从 Windows 注册表中保存的工作区中检索窗口位置

Posted

技术标签:

【中文标题】从 Windows 注册表中保存的工作区中检索窗口位置【英文标题】:Retrieve windows placement from saved workspace in Windows Registry 【发布时间】:2019-01-23 12:15:11 【问题描述】:

我有一个 MFC 应用程序,它会自动将其工作区(窗口位置、打开的窗格、大小等)保存并恢复到 Windows 注册表(例如 HKCU\Software\foo\bar\Workspace)。它工作正常。

现在我有兴趣在加载任何其他窗口之前显示启动屏幕(用户要求)。此初始屏幕必须显示在显示应用程序主窗口的同一屏幕中。

我注意到注册表中有一个值HKCU\Software\foo\bar\Workspace\WindowPlacement\MainWindowRect,我猜它包含有关窗口左上角和大小的信息。有了这些信息,我就能获得正确的屏幕编号(如果对如何操作感兴趣,请参阅 this other post)。

如何获取和解释 MainWindowRect 值?

【问题讨论】:

【参考方案1】:

据我所知,MainWindowRect 恰好是RECT 结构的直接内存转储。一个简单的演员就足以得到窗口的矩形。

这里是获取值以及相关监视器的完整代码 sn-p:

// Assumes SetRegistryKey has been already called
if (const auto hKey = AfxGetApp()->GetSectionKey("Workspace\\WindowPlacement")) 
  DWORD dwReturn[32];
  DWORD dwBufSize = sizeof(dwReturn);
  if (RegQueryValueEx(hKey, "MainWindowRect", 0, 0, (LPBYTE)dwReturn, &dwBufSize) == ERROR_SUCCESS) 
    const auto rectWindow = *(RECT*)dwReturn;

    // Get monitor index from window's rect
    const auto hMonitor = MonitorFromRect(&rectWindow, MONITOR_DEFAULTTONEAREST);
    const auto iMonitorIndex = GetMonitorIndex(hMonitor); // see linked post for GetMonitorIndex implementation
  
  RegCloseKey(hKey);

【讨论】:

以上是关于从 Windows 注册表中保存的工作区中检索窗口位置的主要内容,如果未能解决你的问题,请参考以下文章

使用“hwnd”注册到窗口消息

Windows消息机制

windows消息机制是怎么一回事?谢谢!

从 NSUserDefault 保存和检索数据时,保存按钮无法正常工作

windows程序消息循环机制

我们如何检索在 iOS 中使用核心数据保存的数据