void sendmirc(HWND hwnd, const char *data) {
HANDLE hmap, hmutex;
char *ptr;
// create the filemapping object
if ((hmap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
0, 1024, "mIRC")) == NULL) return;
// at this point we SHOULD check GetLastError() to see if it's set to
// ERROR_ALREADY_EXISTS; that's how mIRC prescribes that it must be done,
// and if all DLL coders did this, we would not need a mutex at all.
// map the shared memory onto our address space
if ((ptr = (char *)MapViewOfFile(hmap, FILE_MAP_ALL_ACCESS, 0, 0, 0)) == NULL) {
CloseHandle(hmap);
return;
}
// the creation and mapping of the virtual file done so far, can not lead to
// synchronization problems on itself; we only need to protect actual access
// so, create or open a mutex that will protect the shared memory access
if ((hmutex = CreateMutex(NULL, FALSE, "mIRC_SendMessage")) != NULL) {
// wait for this mutex to be released - if it is currently locked, wait!
WaitForSingleObject(hmutex, INFINITE);
// now that we hold the mutex, we can access the shared memory safely
lstrcpyn(ptr, data, 4096);
// and tell mIRC to execute our command
SendMessage(hwnd, WM_USER + 200, 0, NULL);
// release and destroy the mutex
ReleaseMutex(hmutex);
CloseHandle(hmutex);
}
// unmap and close the filemapping
UnmapViewOfFile(ptr);
CloseHandle(hmap);
}