nakE
nakE

Reputation: 362

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

I make a program that get the console handle and then move it on the screen like animation, make it "fly" on the screen, move it automatically.

My program takes the resolution of the screen, takes the console handle, and then move it with the MoveWindow function.

My problem is that the window doesn't move at all, and I don't get any errors.

My Code:

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

EDIT:

With the help of the comments you wrote to me, I changed the code.

But now the size of the console is changing, and the console is not moving at all.

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

Second Edit:

The width and the height are the size of the console, so I removed it, and changed the parameters to 100, 100.

Upvotes: 1

Views: 402

Answers (1)

user10986393
user10986393

Reputation:

Here's a really simplified version of what you're trying to do that slides the window down and to the right. I took out the randomness because it was difficult to tell intent from the example. I've also added a limitation to how long the window moves before program termination.

Use this as a starting point for what you want to accomplish.

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

Upvotes: 1

Related Questions