1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#include <winsock2.h>
#include <gdiplus.h>
#include <afxwin.h>

using namespace Gdiplus;


class Socket
{
private:
WSADATA m_wsaData;
SOCKET m_sock;
sockaddr_in m_serverAddr;

public:
Socket() : m_sock(INVALID_SOCKET) {}

bool Init()
{
if (WSAStartup(MAKEWORD(2, 2), &m_wsaData) != 0)
{
return false;
}
return true;
}


bool Create(int af, int type, int protocol)
{
m_sock = socket(af, type, protocol);
if (m_sock == INVALID_SOCKET)
{
return false;
}
return true;
}


bool Connect(const char* ip, unsigned short port)
{
m_serverAddr.sin_family = AF_INET;
m_serverAddr.sin_port = htons(port);
m_serverAddr.sin_addr.S_un.S_addr = inet_addr(ip);
if (connect(m_sock, (sockaddr*)&m_serverAddr, sizeof(m_serverAddr)) == SOCKET_ERROR)
{
return false;
}
return true;
}


int Send(const char* buf, int len)
{
return send(m_sock, buf, len, 0);
}


int Receive(char* buf, int len)
{
return recv(m_sock, buf, len, 0);
}


void Close()
{
closesocket(m_sock);
m_sock = INVALID_SOCKET;
}


void Cleanup()
{
WSACleanup();
}
};


class RemoteDesktop
{
private:
Socket m_socket;
Image* m_image;

public:
RemoteDesktop() : m_image(NULL) {}

bool Connect(const char* ip, unsigned short port)
{
if (!m_socket.Init())
{
return false;
}
if (!m_socket.Create(AF_INET, SOCK_STREAM, IPPROTO_TCP))
{
return false;
}
if (!m_socket.Connect(ip, port))
{
return false;
}
return true;
}

void Disconnect()
{
m_socket.Close();
m_socket.Cleanup();
delete m_image;
m_image = NULL;
}


bool GetScreenshot()
{

const char* cmd = "screenshot";
m_socket.Send(cmd, strlen(cmd));


int size;
m_socket.Receive((char*)&size, sizeof(size));


char* data = new char[size];


int bytesReceived = 0;
while (bytesReceived < size)
{
int count = m_socket.Receive(data + bytesReceived, size - bytesReceived);
if (count <= 0)
{
delete[] data;
return false;
}
bytesReceived += count;
}


delete m_image;
m_image = new Image(data, size);
delete[] data;

return true;
}


Image* GetImage() const
{
return m_image;
}


void MoveMouse(int x, int y)
{

const char* cmd = "mouse move";
m_socket.Send(cmd, strlen(cmd));
m_socket.Send((char*)&x, sizeof(x));
m_socket.Send((char*)&y, sizeof(y));
}


void ClickMouse(int x, int y)
{

const char* cmd = "mouse click";
m_socket.Send(cmd, strlen(cmd));
m_socket.Send((char*)&x, sizeof(x));
m_socket.Send((char*)&y, sizeof(y));
}


void InputKey(int keyCode)
{

const char* cmd = "key input";
m_socket.Send(cmd, strlen(cmd));
m_socket.Send((char*)&keyCode, sizeof(keyCode));
}
};


class RemoteDesktopDialog : public CDialog
{
private:
RemoteDesktop m_rd;

public:

RemoteDesktopDialog() : CDialog(IDD_DIALOG1) {}

protected:
virtual void DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}

public:

bool Connect(const char* ip, unsigned short port)
{
return m_rd.Connect(ip, port);
}


void Disconnect()
{
m_rd.Disconnect();
}
protected:

afx_msg void OnPaint()
{
CPaintDC dc(this);
CRect rect;
GetClientRect(&rect);

Image* image = m_rd.GetImage();
if (image != NULL)
{
Graphics graphics(dc);
graphics.DrawImage(image, rect);
}
}


afx_msg void OnMouseMove(UINT nFlags, CPoint point)
{
m_rd.MoveMouse(point.x, point.y);
}

afx_msg void OnLButtonDown(UINT nFlags, CPoint point)
{
m_rd.ClickMouse(point.x, point.y);
}


afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
m_rd.InputKey(nChar);
}
DECLARE_MESSAGE_MAP()
};

BEGIN_MESSAGE_MAP(RemoteDesktopDialog, CDialog)
ON_WM_PAINT()
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONDOWN()
ON_WM_KEYDOWN()
END_MESSAGE_MAP()

int main()
{

GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

RemoteDesktopDialog dlg;
dlg.DoModal();


GdiplusShutdown(gdiplusToken);
return 0;
}

在这段代码中,我们定义了三个类:Socket、RemoteDesktop 和 RemoteDesktopDialog。Socket 类封装了网络通信的相关操作,RemoteDesktop 类用于控制远程桌面,RemoteDesktopDialog 类用于显示远程桌面的界面。

需要注意的是,这段代码使用了 MFC 库来绘制界面,因此需要在 Visual Studio 中创建一个 MFC 应用程序,并在对话框资源中添加一个对话框。然后将上面的代码放入主窗口类的 .cpp 文件中,并在 .h 文件中声明相应的消息映射函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
#include <Windows.h>
#include <GdiPlus.h>
#include <winsock2.h>
#include<iostream>
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "ws2_32.lib")
using namespace std;
using namespace Gdiplus;


class Socket
{
private:
WSADATA m_wsaData;
SOCKET m_sock;
sockaddr_in m_serverAddr;
sockaddr_in m_clientAddr;

public:
Socket() : m_sock(INVALID_SOCKET) {}

bool Init()
{
if (WSAStartup(MAKEWORD(2, 2), &m_wsaData) != 0)
{
return false;
}
return true;
}


bool Create(int af, int type, int protocol)
{
m_sock = socket(af, type, protocol);
if (m_sock == INVALID_SOCKET)
{
return false;
}
return true;
}

bool Bind(unsigned short port)
{
memset(&m_serverAddr, 0, sizeof(m_serverAddr));
m_serverAddr.sin_family = AF_INET;
m_serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
m_serverAddr.sin_port = htons(port);
if (bind(m_sock, (sockaddr*)&m_serverAddr, sizeof(m_serverAddr)) == SOCKET_ERROR)
{
return false;
}
return true;
}

bool Listen(int backlog)
{
if (listen(m_sock, backlog) == SOCKET_ERROR)
{
return false;
}
return true;
}


bool Accept(Socket& client)
{
int addrLen = sizeof(m_clientAddr);
client.m_sock = accept(m_sock, (sockaddr*)&m_clientAddr, &addrLen);
if (client.m_sock == INVALID_SOCKET)
{
return false;
}
return true;
}


int Receive(char* buffer, int len)
{
return recv(m_sock, buffer, len, 0);
}


int Send(const char* buffer, int len)
{
return send(m_sock, buffer, len, 0);
}


void Close()
{
closesocket(m_sock);
m_sock = INVALID_SOCKET;
}


void Cleanup()
{
WSACleanup();
}
};


class RemoteDesktopServer
{
private:
Socket m_socket;

public:

bool Init(unsigned short port)
{
if (!m_socket.Init())
{
return false;
}
if (!m_socket.Create(AF_INET, SOCK_STREAM, IPPROTO_TCP))
{
return false;
}
if (!m_socket.Bind(port))
{
return false;
}
if (!m_socket.Listen(10))
{
return false;
}
return true;
}

void Run()
{

while (true)
{
Socket client;
if (!m_socket.Accept(client))
{
continue;
}


HANDLE hThread = CreateThread(NULL, 0, ClientThreadProc, &client, 0, NULL);
if (hThread == NULL)
{
client.Close();
continue;
}
CloseHandle(hThread);
}
}
private:

static DWORD WINAPI ClientThreadProc(LPVOID lpParam)
{
Socket* pClient = (Socket*)lpParam;

while (true)
{

char cmd[256];
int len = pClient->Receive(cmd, sizeof(cmd));
if (len <= 0)
{
break;
}


if (strcmp(cmd, "screenshot") == 0)
{

HandleScreenshotRequest(*pClient);
}
else if (strcmp(cmd, "mouse move") == 0)
{

int x, y;
pClient->Receive((char*)&x, sizeof(x));
pClient->Receive((char*)&y, sizeof(y));
HandleMouseMoveRequest(x, y);
}
else if (strcmp(cmd, "mouse click") == 0)
{

int x, y;
pClient->Receive((char*)&x, sizeof(x));
pClient->Receive((char*)&y, sizeof(y));
HandleMouseClickRequest(x, y);
}
else if (strcmp(cmd, "key input") == 0)
{

char key;
pClient->Receive(&key, sizeof(key));
HandleKeyInputRequest(key);
}
else
{
break;
}
}

pClient->Close();
delete pClient;
return 0;
}


static void HandleScreenshotRequest(Socket& client)
{

int width = GetSystemMetrics(SM_CXSCREEN);
int height = GetSystemMetrics(SM_CYSCREEN);


HDC hdcMem = CreateCompatibleDC(NULL);
if (hdcMem == NULL)
{
return;
}


HBITMAP hbm = CreateCompatibleBitmap(GetDC(NULL), width, height);
if (hbm == NULL)
{
DeleteDC(hdcMem);
return;
}


HBITMAP hbmOld = (HBITMAP)SelectObject(hdcMem, hbm);
if (hbmOld == NULL)
{
DeleteObject(hbm);
DeleteDC(hdcMem);
return;
}


if (!BitBlt(hdcMem, 0, 0, width, height, GetDC(NULL), 0, 0, SRCCOPY))
{
SelectObject(hdcMem, hbmOld);
DeleteObject(hbm);
DeleteDC(hdcMem);
return;
}


BITMAPINFOHEADER bih;
memset(&bih, 0, sizeof(bih));
bih.biSize = sizeof(bih);
bih.biWidth = width;
bih.biHeight = -height;
bih.biPlanes = 1;
bih.biBitCount = 24;
bih.biCompression = BI_RGB;
BYTE* pBuf = NULL;
HBITMAP hbmDib = CreateDIBSection(hdcMem, (BITMAPINFO*)&bih, DIB_RGB_COLORS, (void**)&pBuf, NULL, 0);
if (hbmDib == NULL)
{
SelectObject(hdcMem, hbmOld);
DeleteObject(hbm);
DeleteDC(hdcMem);
return;
}

if (!SelectObject(hdcMem, hbmDib))
{
DeleteObject(hbmDib);
SelectObject(hdcMem, hbmOld);
DeleteObject(hbm);
DeleteDC(hdcMem);
return;
}

if (!SendScreenshot(client, pBuf, width, height))
{
DeleteObject(hbmDib);
SelectObject(hdcMem, hbmOld);
DeleteObject(hbm);
DeleteDC(hdcMem);
return;
}


DeleteObject(hbmDib);
SelectObject(hdcMem, hbmOld);
DeleteObject(hbm);
DeleteDC(hdcMem);
}


static bool SendScreenshot(Socket& client, BYTE* pBuf, int width, int height)
{

GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);


Bitmap bmp(width, height, width * 3, PixelFormat24bppRGB, pBuf);
CLSID clsid;
GetEncoderClsid(L"image/jpeg", &clsid);
IStream* pStream = NULL;
bmp.Save(L"screenshot.jpg", &clsid, NULL);
if (CreateStreamOnHGlobal(NULL, TRUE, &pStream) != S_OK)
{
GdiplusShutdown(gdiplusToken);
return false;
}
bmp.Save(pStream, &clsid, NULL);
HGLOBAL hGlobal = NULL;
if (GetHGlobalFromStream(pStream, &hGlobal) != S_OK)
{
pStream->Release();
GdiplusShutdown(gdiplusToken);
return false;
}
ULONG cbSize = GlobalSize(hGlobal);
BYTE* pJpegBuf = (BYTE*)GlobalLock(hGlobal);
if (pJpegBuf == NULL)
{
pStream->Release();
GdiplusShutdown(gdiplusToken);
return false;
}
LARGE_INTEGER li;
li.QuadPart = 0;
if (pStream->Seek(li, STREAM_SEEK_SET, NULL) != S_OK)
{
GlobalFree(pJpegBuf);
pStream->Release();
GdiplusShutdown(gdiplusToken);
return false;
}
if (pStream->Read(pJpegBuf, cbSize, NULL) != S_OK)
{
GlobalFree(pJpegBuf);
pStream->Release();
GdiplusShutdown(gdiplusToken);
return false;
}
pStream->Release();
GdiplusShutdown(gdiplusToken);

if (client.Send((char*)&cbSize, sizeof(cbSize)) <= 0)
{
GlobalFree(pJpegBuf);
return false;
}


if (client.Send((char*)pJpegBuf, cbSize) <= 0)
{
GlobalFree(pJpegBuf);
return false;
}


GlobalFree(pJpegBuf);
return true;
}


static void GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
UINT num = 0, size = 0;
GetImageEncodersSize(&num, &size);
if (size == 0)
{
return;
}
ImageCodecInfo* pImageCodecInfo = (ImageCodecInfo*)malloc(size);
if (pImageCodecInfo == NULL)
{
return;
}
GetImageEncoders(num, size, pImageCodecInfo);
for (UINT i = 0; i < num; ++i)
{
if (wcscmp(pImageCodecInfo[i].MimeType, format) == 0)
{
*pClsid = pImageCodecInfo[i].Clsid;
free(pImageCodecInfo);
return;
}
}
free(pImageCodecInfo);
}

static void HandleMouseMoveRequest(int x, int y)
{

int width = GetSystemMetrics(SM_CXSCREEN);
int height = GetSystemMetrics(SM_CYSCREEN);


double fx = (double)x / 65535.0;

SetCursorPos(x, y);
}


static void HandleMouseClickRequest(int x, int y)
{

int width = GetSystemMetrics(SM_CXSCREEN);
int height = GetSystemMetrics(SM_CYSCREEN);


double fx = (double)x / 65535.0;
double fy = (double)y / 65535.0;
int cx = (int)(fx * width);
int cy = (int)(fy * height);


SetCursorPos(cx, cy);


INPUT input;
memset(&input, 0, sizeof(input));
input.type = INPUT_MOUSE;
input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;
SendInput(1, &input, sizeof(input));
}


static void HandleKeyInputRequest(char key)
{

HKL layout = GetKeyboardLayout(0);
UINT vk = MapVirtualKeyExA(VkKeyScanExA(key, layout), 0, layout);


INPUT input;
memset(&input, 0, sizeof(input));
input.type = INPUT_KEYBOARD;
input.ki.wVk = vk;
SendInput(1, &input, sizeof(input));
}
private:
Socket m_socket;
};

int main()
{
RemoteDesktopServer server;
if (!server.Init(5555))
{
cout<<"启动服务器失败!"<<endl;
return 1;
}
server.Run();
return 0;
}