#include
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PSTR szCmdLine,
int iCmdShow)
{
static TCHAR szAppName[] = TEXT("Line");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
int cxScreen, cyScreen;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if (!RegisterClass(&wndclass))
{
MessageBox(NULL, TEXT("This program requires Windows NT!"),
szAppName, MB_ICONERROR);
return 0;
}
cxScreen = GetSystemMetrics(SM_CXSCREEN);
cyScreen = GetSystemMetrics(SM_CYSCREEN);
hwnd = CreateWindow(szAppName,
TEXT("Line Demo"),
WS_OVERLAPPEDWINDOW,
cxScreen * 7 / 20,
cyScreen / 3.5,
cxScreen * 3 / 10,
cyScreen / 2,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
HDC dc = GetWindowDC(GetDesktopWindow());
int ff(float x)
{
return (int)(x < 0 ? x - 0.5 : x + 0.5);
}
void DDALine(HDC hdc,int x0, int y0, int x1, int y1, COLORREF color)
{
float dx, dy, x, y;
int numb = abs(x1 - x0) > abs(y1 - y0) ? abs(x1 - x0) : abs(y1 - y0);
x = (float)(x0);
y = (float)(y0);
dx = (float)(x1 - x0) / numb;
dy = (float)(y1 - y0) / numb;
for (int i = 0; i <= numb; i++)
{
SetPixel(dc, ff(x), ff(y), color);
Sleep(1);
x += dx;
y += dy;
}
Sleep(900);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
//起点和终点
static POINT start, end;
HPEN hPen;
HDC hdc;
PAINTSTRUCT ps;
switch (message)
{
case WM_CREATE:
//初始化直线起点和终点
start.x = -1;
start.y = -1;
end.x = 0;
end.y = 0;
return 0;
//画直线
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
hPen = CreatePen(PS_SOLID, 1, RGB(255, 235, 0)); //画笔格式
SelectObject(hdc, hPen);
MoveToEx(hdc, start.x, start.y, NULL);
DDALine(hdc,start.x, start.y, end.x, end.y, RGB(0, 0, 0));
DeleteObject(hPen);
EndPaint(hwnd, &ps);
return 0;
//获取起点,使用start记录鼠标落下的位子
case WM_LBUTTONDOWN:
start.x = LOWORD(lParam);
start.y = HIWORD(lParam);
return 0;
//获取终点,使用end记录鼠标弹起的位子
case WM_LBUTTONUP:
end.x = LOWORD(lParam);
end.y = HIWORD(lParam);
InvalidateRect(hwnd, NULL, FALSE);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}