#include <WindowsX.h>
HANDLE s_hFileMap=NULL;
// This macro evaluates to the number of elements in an array.
#define chDIMOF(Array) (sizeof(Array) / sizeof(Array[0]))
inline void chMB(PCSTR s) {
char szTMP[128];
GetModuleFileNameA(NULL, szTMP, chDIMOF(szTMP));
MessageBoxA(GetActiveWindow(), s, szTMP, MB_OK);
}
void CMyMMFShareDlg::OnCreatefile()
{
// Create a paging file-backed MMF to contain the edit control text.
// The MMF is 4 KB at most and is named MMFSharedData.
s_hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
PAGE_READWRITE, 0, 4 * 1024, TEXT("MMFSharedData"));
if (s_hFileMap != NULL) {
if (GetLastError() == ERROR_ALREADY_EXISTS) {
chMB("Mapping already exists - not created.");
CloseHandle(s_hFileMap);
} else {
// File mapping created successfully.
// Map a view of the file into the address space.
PVOID pView = MapViewOfFile(s_hFileMap,
FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (pView != NULL) {
// Put edit text into the MMF.
//Edit_GetText(GetDlgItem( IDC_DATA),
// (PTSTR) pView, 4 * 1024);
GetDlgItemText(IDC_DATA,(PTSTR) pView, 4 * 1024);
// Protect the MMF storage by unmapping it.
UnmapViewOfFile(pView);
// The user can't create another file right now.
//Button_Enable(hwndCtl, FALSE);
//Button_Enable(GetDlgItem(IDC_CREATEFILE), FALSE);
GetDlgItem(IDC_CREATEFILE)->EnableWindow(FALSE);
// The user closed the file.
//Button_Enable(GetDlgItem(hwnd, IDC_CLOSEFILE), TRUE);
GetDlgItem(IDC_CLOSEFILE)->EnableWindow(TRUE);
} else {
chMB("Can't map view of file.");
}
}
} else {
chMB("Can't create file mapping.");
}
}
void CMyMMFShareDlg::OnClosefile()
{
if (CloseHandle(s_hFileMap)) {
// User closed the file, fix up the buttons.
//Button_Enable(GetDlgItem(hwnd, IDC_CREATEFILE), TRUE);
GetDlgItem(IDC_CREATEFILE)->EnableWindow(TRUE);
//Button_Enable(hwndCtl, FALSE);
GetDlgItem(IDC_CLOSEFILE)->EnableWindow(FALSE);
}
}
void CMyMMFShareDlg::OnOpenfile()
{
// See if a memory-mapped file named MMFSharedData already exists.
HANDLE hFileMapT = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE,
FALSE, TEXT("MMFSharedData"));
if (hFileMapT != NULL) {
// The MMF does exist, map it into the process's address space.
PVOID pView = MapViewOfFile(hFileMapT,
FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (pView != NULL) {
// Put the contents of the MMF into the edit control.
//Edit_SetText(GetDlgItem(hwnd, IDC_DATA), (PTSTR) pView);
GetDlgItem(IDC_DATA)->SetWindowText((PTSTR) pView);
UnmapViewOfFile(pView);
} else {
chMB("Can't map view.");
}
CloseHandle(hFileMapT);
} else {
chMB("Can't open mapping.");
}
}