有没有办法像动画一样移动控制台窗口?

Is there a way I can move my console window like animation?

本文关键字:一样 移动 控制台 窗口 动画 有没有      更新时间:2023-10-16

我制作了一个程序来获取控制台句柄,然后像动画一样在屏幕上移动它,让它在屏幕上"飞",自动移动它。

我的程序采用屏幕的分辨率,获取控制台句柄,然后使用MoveWindow函数移动它。

我的问题是窗口根本没有移动,而且我没有收到任何错误。

我的代码:

#include <iostream>
#include <Windows.h>
#include <ctime>
using namespace std;
int main()
{
srand(time(nullptr));
POINT current_position;
while (true) {
int offset = rand() % 2;
int x_direction = rand() % 2 == 1 ? 1 : -1;
int y_direction = rand() % 2 == 1 ? 1 : -1;
int width = GetSystemMetrics(SM_CXSCREEN);
int height = GetSystemMetrics(SM_CYSCREEN);
HWND hwndConsole = GetWindow(GetConsoleWindow(), (UINT)&current_position);
MoveWindow(hwndConsole, current_position.x + (offset * x_direction), current_position.y + (offset * y_direction), width, height, TRUE);
Sleep(10);
}
return 0;
}

编辑:

在您写给我的评论的帮助下,我更改了代码。

但是现在控制台的大小在变化,控制台根本没有移动。

#include <iostream>
#include <Windows.h>
#include <ctime>
using namespace std;
int main()
{
srand(time(nullptr));
POINT current_position{};
while (true) {
HWND hwndConsole = GetConsoleWindow();
int offset = rand() % 2;
int x_direction = rand() % 2 == 1 ? 1 : -1;
int y_direction = rand() % 2 == 1 ? 1 : -1;
int width = GetSystemMetrics(SM_CXSCREEN);
int height = GetSystemMetrics(SM_CYSCREEN);
BOOL hwndMove = MoveWindow(hwndConsole, current_position.x + (offset * x_direction), current_position.y + (offset * y_direction), width, height, TRUE);
if (hwndMove == FALSE) {
cout << "Failed! & Error Code: " << GetLastError();
}
Sleep(10);
}
return 0;
}

第二次编辑:

widthheight是控制台的大小,所以我删除了它,并将参数更改为 100、100。

这是一个你正在尝试做的事情的真正简化版本,它将窗口向下和向右滑动。我去掉了随机性,因为很难从例子中分辨出意图。我还添加了对程序终止前窗口移动时间的限制。

将此作为您想要完成的工作的起点。

#include <Windows.h>
int main()
{
HWND hwndConsole = GetConsoleWindow();
for (int i = 0; i < 200; i++)
{
RECT position;
GetWindowRect(hwndConsole, &position);
MoveWindow(hwndConsole, position.left + 3, position.top + 3, 300, 300, TRUE);
Sleep(10);
}
return 0;
}