/
client_windows.c
91 lines (70 loc) · 2.06 KB
/
client_windows.c
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
#include "client_windows.h"
char* geterror(const char* sender) {
DWORD code = GetLastError();
char* msg;
DWORD n = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, code, 0, (LPSTR)&msg, 0, NULL);
char* buf = (char*)malloc((size_t)n + strlen(sender) + 3);
sprintf(buf, "%s: %s", sender, msg);
return buf;
}
char* CopyString(const char* str) {
if (!OpenClipboard(NULL)) {
return geterror("CopyString");
}
// copy our UTF-8 text into a wchar string stored in the global handle
size_t n = 0;
mbstowcs_s(&n, NULL, 0, str, 0);
// alloc and lock global memory
HGLOBAL hMem = GlobalAlloc(GMEM_SHARE | GMEM_MOVEABLE, n*sizeof(wchar_t) + 1);
LPTSTR glob = (LPTSTR)GlobalLock(hMem);
mbstowcs_s(&n, glob, n + 1, str, n);
GlobalUnlock(hMem);
if (!SetClipboardData(CF_UNICODETEXT, hMem)) {
return geterror("SetClipboardData");
}
if (!CloseClipboard()) {
return geterror("CloseClipboard");
}
return NULL;
}
char* CryptPassword(const char* str, int inSize, void** out, int* outSize, int encrypt) {
DATA_BLOB input, output;
input.cbData = (DWORD)inSize + 1;
input.pbData = (BYTE*)str;
BOOL ok;
if (encrypt) {
ok = CryptProtectData(&input, NULL, NULL, NULL, NULL, 0, &output);
if (!ok) {
return geterror("CryptProtectData");
}
} else {
ok = CryptUnprotectData(&input, NULL, NULL, NULL, NULL, 0, &output);
if (!ok) {
return geterror("CryptUnprotectData");
}
}
*out = output.pbData;
*outSize = output.cbData;
return NULL;
}
HANDLE GetTermInfo(CONSOLE_SCREEN_BUFFER_INFO* s) {
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hOut, s);
return hOut;
}
void ClearLine(void) {
CONSOLE_SCREEN_BUFFER_INFO s;
HANDLE out = GetTermInfo(&s);
COORD pos = { 0, s.dwCursorPosition.Y };
DWORD n;
FillConsoleOutputCharacter(out, ' ', s.dwSize.X, pos, (LPDWORD)(&n));
SetConsoleCursorPosition(out, pos);
}
void MoveUp(void) {
CONSOLE_SCREEN_BUFFER_INFO s;
HANDLE out = GetTermInfo(&s);
COORD pos = { 0, s.dwCursorPosition.Y - 2 };
SetConsoleCursorPosition(out, pos);
}