如何防止控制台窗口超出屏幕范围?

时间:2012-06-01 12:35:08

标签: c++ windows winapi console

如果控制台应用程序启动并且系统为其创建控制台窗口,但有时此窗口是在这样的坐标中创建的,其中某些内容从右侧屏幕边缘滑出。然后用户必须使用鼠标来显示所有内容。

如何应对? 用什么函数来检测控制台窗口的右上角坐标? 然后我将能够检查它是否在屏幕之外并将窗口移动到所需的距离。

移动窗口有什么功能? 或者也许有一个解决方案可以防止窗口移动到屏幕之外?

1 个答案:

答案 0 :(得分:1)

这是一个完全多监视器感知和任务栏感知的实现,可以完成您所描述的内容。

#include <Windows.h>

int main()
{
  ClampConsoleToScreen();
  return 0;
}

void ClampConsoleToScreen()
{
  HWND window = GetConsoleWindow();
  RECT windowRect;
  GetWindowRect(window, &windowRect);
  HMONITOR monitor = MonitorFromWindow(window, MONITOR_DEFAULTTOPRIMARY);
  MONITORINFO mi;
  memset(&mi, 0, sizeof(mi));
  mi.cbSize = sizeof(mi);
  GetMonitorInfo(monitor, &mi);

  int adj, any;

  adj = 0;
  any = 0;
  if (windowRect.right > mi.rcWork.right)
  {
    // Get negative adjustment value to move it left onto screen
    adj = mi.rcWork.right - windowRect.right;
  }
  if (windowRect.left < mi.rcWork.left)
  {
    // Get positive adjustment value to move it right onto screen
    adj = mi.rcWork.left - windowRect.left;
  }
  windowRect.left += adj;
  windowRect.right += adj;
  any |= adj;

  adj = 0;
  if (windowRect.bottom > mi.rcWork.bottom)
  {
    // Get negative adjustment value to move it up onto screen
    adj = mi.rcWork.bottom - windowRect.bottom;
  }
  if (windowRect.top < mi.rcWork.top)
  {
    // Get positive adjustment value to move it down onto screen
    adj = mi.rcWork.top - windowRect.top;
  }
  windowRect.top += adj;
  windowRect.bottom += adj;
  any |= adj;

  if (any)
  {
    MoveWindow(window,
      windowRect.left,
      windowRect.top,
      windowRect.right - windowRect.left,
      windowRect.bottom - windowRect.top, TRUE);
  }
}