【问题标题】:Is there a way I can move my console window like animation?有没有办法像动画一样移动控制台窗口?
【发布时间】: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)&current_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;
}

第二次编辑:

widthheight是控制台的大小,所以我把它去掉了,把参数改成100、100。

【问题讨论】:

  • @Dialectus 我认为不,用户想将他的控制台居中,将其移动到不同的位置。在我的问题中,我想让它像动画一样移动,让它自动移动。
  • MoveWindow 的返回值是多少?如果是错误,那么GetLastError 的返回值是什么?
  • 错误检查对于 winapi 函数不是可选的。那个 GetWindow() 调用没有意义,删除它以继续前进。
  • @Alejandro 嘿,错误代码是:1400 ,无效的窗口句柄。

标签: c++ windows


【解决方案1】:

这是您尝试执行的操作的真正简化版本,它会将窗口向下和向右滑动。我去掉了随机性,因为很难从示例中分辨出意图。我还添加了对程序终止前窗口移动时间的限制。

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

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多