【发布时间】:2019-12-10 19:16:24
【问题描述】:
我制作了一个获取控制台句柄的程序,然后像动画一样在屏幕上移动它,让它在屏幕上“飞”,自动移动它。
我的程序获取屏幕分辨率,获取控制台句柄,然后使用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)¤t_position);
MoveWindow(hwndConsole, current_position.x + (offset * x_direction), current_position.y + (offset * y_direction), width, height, TRUE);
Sleep(10);
}
return 0;
}
编辑:
在你给我写的cmets的帮助下,我改了代码。
但是现在控制台的大小在变化,控制台根本不动。
#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;
}
第二次编辑:
width和height是控制台的大小,所以我把它去掉了,把参数改成100、100。
【问题讨论】:
-
@Dialectus 我认为不,用户想将他的控制台居中,将其移动到不同的位置。在我的问题中,我想让它像动画一样移动,让它自动移动。
-
MoveWindow的返回值是多少?如果是错误,那么GetLastError的返回值是什么? -
错误检查对于 winapi 函数不是可选的。那个 GetWindow() 调用没有意义,删除它以继续前进。
-
@Alejandro 嘿,错误代码是:1400 ,无效的窗口句柄。