forked from notepad-plus-plus/nppShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SharedState.cpp
60 lines (51 loc) · 1.8 KB
/
SharedState.cpp
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
#include "pch.h"
#include "SharedState.h"
#include "LoggingHelper.h"
using namespace NppShell::Helpers;
extern LoggingHelper g_loggingHelper;
SharedState::SharedState()
{
// Create or open the shared memory mapped file
hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(int), L"Local\\BaseNppExplorerCommandHandlerSharedStateMemory");
if (hFileMapping == NULL)
{
g_loggingHelper.LogMessage(L"SharedState::ctor", L"Failed to create or open shared memory mapped file");
return;
}
// Create a mutex to synchronize access to the shared memory
hMutex = CreateMutex(NULL, FALSE, L"Local\\BaseNppExplorerCommandHandlerSharedStateMutex");
if (hMutex == NULL)
{
g_loggingHelper.LogMessage(L"SharedState::ctor", L"Failed to create mutex");
CloseHandle(hFileMapping);
return;
}
// Map the shared memory into the current process's address space
pState = (CounterState*)MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(CounterState));
if (pState == NULL)
{
MessageBox(NULL, L"Failed to map shared memory", L"SharedState", MB_OK | MB_ICONERROR);
CloseHandle(hMutex);
CloseHandle(hFileMapping);
return;
}
}
SharedState::~SharedState()
{
// Unmap the shared memory from the current process's address space
UnmapViewOfFile(pState);
// Close the mutex and the shared memory mapped file
CloseHandle(hMutex);
CloseHandle(hFileMapping);
}
CounterState SharedState::GetState() const
{
return *pState;
}
void SharedState::SetState(CounterState state)
{
WaitForSingleObject(hMutex, INFINITE);
*pState = state;
g_loggingHelper.LogMessage(L"SharedState::SetState", L"Set shared state to: " + to_wstring(state));
ReleaseMutex(hMutex);
}