//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit2.h"
#include "Unit1.h"
#include "Windowsx.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm2 *Form2;
//---------------------------------------------------------------------------
__fastcall TForm2::TForm2(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
WNDPROC oldWindowProc = NULL;
int xWndOffset;
int yWndOffset;
bool isDragging = false;
int snapThreshold = 100;
void moveSnapWindow(HWND hwnd, int x, int y)
{
int snapThreshold_L = Form1->Left + Form1->Width + snapThreshold;
int snapThreshold_T = Form1->Top + Form1->Height + snapThreshold;
RECT rc;
GetWindowRect(hwnd, &rc);
int scr_w = Form1->Width + Form1->Left;//GetSystemMetrics(SM_CXSCREEN);
int scr_h = Form1->Height + Form1->Top;//GetSystemMetrics(SM_CYSCREEN);
if(abs(x) < snapThreshold) x = 0;
if(abs(y) < snapThreshold) y = 0;
if(abs(scr_w - (x + rc.right - rc.left)) < snapThreshold_L) x = scr_w;// - (rc.right - rc.left);
if(abs(scr_h - (y + rc.bottom - rc.top)) < snapThreshold) y = scr_h - (rc.bottom - rc.top);
MoveWindow(hwnd, x, y, rc.right - rc.left, rc.bottom - rc.top, TRUE);
}
LRESULT CALLBACK newWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if(msg == WM_NCLBUTTONDOWN && wParam == HTCAPTION)
{
RECT rc;
GetWindowRect(hwnd, &rc);
xWndOffset = GET_X_LPARAM(lParam) - rc.left;
yWndOffset = GET_Y_LPARAM(lParam) - rc.top;
SetCapture(hwnd);
isDragging = true;
return 0;
}
if(isDragging && msg == WM_MOUSEMOVE)
{
POINT pt = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
ClientToScreen(hwnd, &pt);
moveSnapWindow(hwnd, pt.x - xWndOffset, pt.y - yWndOffset);
return 0;
}
if(isDragging && msg == WM_LBUTTONUP)
{
isDragging = false;
if(hwnd == GetCapture())
ReleaseCapture();
POINT pt = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
ClientToScreen(hwnd, &pt);
moveSnapWindow(hwnd, pt.x - xWndOffset, pt.y - yWndOffset);
return 0;
}
if(isDragging && msg == WM_CAPTURECHANGED)
{
isDragging = false;
}
return CallWindowProc(oldWindowProc, hwnd, msg, wParam, lParam);
}
void __fastcall TForm2::FormCreate(TObject *Sender)
{
oldWindowProc = (WNDPROC) GetWindowLongPtr(Handle, GWLP_WNDPROC);
SetWindowLongPtr(Handle, GWLP_WNDPROC, (LONG_PTR) &newWindowProc);
}
//---------------------------------------------------------------------------