Skip to content

Instantly share code, notes, and snippets.

@kingsamchen
Created December 8, 2013 08:59
Show Gist options
  • Select an option

  • Save kingsamchen/7854845 to your computer and use it in GitHub Desktop.

Select an option

Save kingsamchen/7854845 to your computer and use it in GitHub Desktop.
const wstring SHUTDOWN_ACK = L"Server Shutdown";
HANDLE g_requestSubmitted;
HANDLE g_requestReturned;
HWND g_mainDlg;
wstring g_requestText;
UINT APIENTRY ServerThreadFunc(PVOID param)
{
bool isShutdown = false;
while (!isShutdown) {
WaitForSingleObject(g_requestSubmitted, INFINITE);
isShutdown = (g_mainDlg == NULL) && (g_requestText == SHUTDOWN_ACK);
if (!isShutdown) {
std::reverse(g_requestText.begin(), g_requestText.end());
}
SetEvent(g_requestReturned);
}
return 0;
}
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// create auto-reset event objects
g_requestSubmitted = CreateEvent(NULL, FALSE, FALSE, NULL);
g_requestReturned = CreateEvent(NULL, FALSE, FALSE, NULL);
ON_SCOPE_EXIT([&]{ CloseHandle(g_requestSubmitted); });
ON_SCOPE_EXIT([&]{ CloseHandle(g_requestReturned); });
// create the server thread
UINT threadId;
HANDLE hThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL,
0,
ServerThreadFunc,
NULL,
0,
&threadId));
ON_SCOPE_EXIT([&]{ CloseHandle(hThread); });
DialogBox(hInstance, MAKEINTRESOURCE(IDD_DLGMAIN), NULL, DlgProc);
g_mainDlg = NULL;
g_requestText = SHUTDOWN_ACK;
SetEvent(g_requestSubmitted);
// wait for server thread to ACK the shutdown and to fully exit
WaitForSingleObject(g_requestReturned, INFINITE);
WaitForSingleObject(hThread, INFINITE);
return 0;
}
void OnClose(HWND hwnd)
{
EndDialog(hwnd, FALSE);
}
BOOL OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)
{
//InitializeSRWLock(&g_srwLock);
g_mainDlg = hwnd;
return TRUE;
}
void OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch (id) {
case IDC_BTN_SUBMIT: {
vector<wchar_t> v(255);
UINT cnt = GetDlgItemText(hwnd, IDC_EDT_REQTXT, &v[0], 255);
g_requestText.assign(v.begin(), v.begin() + cnt);
SetEvent(g_requestSubmitted);
WaitForSingleObject(g_requestReturned, INFINITE);
SetDlgItemText(hwnd, IDC_EDT_RETTXT, g_requestText.c_str());
}
break;
}
}
INT_PTR CALLBACK DlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
HANDLE_MSG(hwnd, WM_INITDIALOG, OnInitDialog);
HANDLE_MSG(hwnd, WM_COMMAND, OnCommand);
HANDLE_MSG(hwnd, WM_CLOSE, OnClose);
default:
return FALSE;
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment