Skip to content

Instantly share code, notes, and snippets.

@Soulstorm50
Created October 29, 2016 09:15
Show Gist options
  • Save Soulstorm50/49753cb2ff2c7fa2006a2224dd00e661 to your computer and use it in GitHub Desktop.
Save Soulstorm50/49753cb2ff2c7fa2006a2224dd00e661 to your computer and use it in GitHub Desktop.
SelfMovingWindow
#include <windows.h>
#include <tchar.h>
#include <time.h>
LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);
VOID CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime);
int screenWidth = 0;
int screenHeight = 0;
int shiftX = 25;
int shiftY = 0;
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpszCmdLine, int nCmdShow)
{
TCHAR szClassWindow[] = L"Win32Application";
screenWidth = GetSystemMetrics(SM_CXSCREEN);
screenHeight = GetSystemMetrics(SM_CYSCREEN);
HWND hWnd;
MSG lpMsg;
WNDCLASSEX wcl;
wcl.cbSize = sizeof(wcl);
wcl.style = CS_HREDRAW | CS_VREDRAW;
wcl.lpfnWndProc = WindowProc;
wcl.cbClsExtra = 0;
wcl.cbWndExtra = 0;
wcl.hInstance = hInst;
wcl.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcl.hCursor = LoadCursor(NULL, IDC_ARROW);
wcl.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wcl.lpszMenuName = NULL;
wcl.lpszClassName = szClassWindow;
wcl.hIconSm = NULL;
if (!RegisterClassEx(&wcl))
return 0;
hWnd = CreateWindowEx(0, szClassWindow, TEXT("Self moving window"), WS_OVERLAPPEDWINDOW,
0, 0, 200, 200, NULL, NULL, hInst, NULL);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
SetTimer(hWnd, 1, 500, TimerProc);
while (GetMessage(&lpMsg, NULL, 0, 0))
{
TranslateMessage(&lpMsg);
DispatchMessage(&lpMsg);
}
return lpMsg.wParam;
}
VOID CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
RECT winRect = {};
GetWindowRect(hwnd, &winRect);
if (shiftX > 0 && shiftY == 0)
{
if (winRect.right == screenWidth)
{
shiftX = 0;
shiftY = 25;
}
else if (winRect.right + shiftX > screenWidth)
{
shiftX = screenWidth - winRect.right;
}
}
else if (shiftX == 0 && shiftY > 0)
{
if (winRect.bottom == screenHeight)
{
shiftX = -25;
shiftY = 0;
}
else if (winRect.bottom + shiftY > screenHeight)
{
shiftY = screenHeight - winRect.bottom;
}
}
else if (shiftX < 0 && shiftY == 0)
{
if (winRect.left == 0)
{
shiftX = 0;
shiftY = -25;
}
else if (winRect.left + shiftX < 0)
{
shiftX = -1 * winRect.left;
}
}
else if (shiftX == 0 && shiftY < 0)
{
if (winRect.top == 0)
{
shiftX = 25;
shiftY = 0;
}
else if (winRect.top + shiftY < 0)
{
shiftY = -1 * winRect.top;
}
}
MoveWindow(hwnd, winRect.left + shiftX, winRect.top + shiftY, 200, 200, TRUE);
}
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment