Ok, then. I started learning C++, and my task is to create a process manager with the Win32 API. It is going to look like this:
I have a TBuffer
class: (Buffer will keep information about the processes)
#pragma once
#include <wtypes.h>
#define BUFFER_SIZE 10
#define WM_UPDATELIST WM_USER
enum TProcessState { psEmpty, psNew, psRunning, psTerminated, psError };
struct TProcessInfo
{
TProcessState State;
char Name[100];
HANDLE Handle;
int PID;
int UserTime, KenelTime;
};
class TBuffer
{
private:
HWND Wnd;
CRITICAL_SECTION cs;
TProcessInfo Buf[BUFFER_SIZE];
public:
TBuffer(HWND AWnd);
~TBuffer();
int Count();
int AddProcess(char *AName);
void Get(int Id, TProcessInfo &Pi);
void Set(int Id, const TProcessInfo Pi);
const char* ProcessStateToString(TProcessState state);
};
The class constructor has the following realization:
TBuffer::TBuffer(HWND AWnd)
{
Wnd = AWnd;
InitializeCriticalSection(&cs);
for (int i = 0; i < BUFFER_SIZE; i++)
{
Buf[i].State = psEmpty;
Buf[i].Handle = 0;
Buf[i].Name[0] = 0;
Buf[i].PID = 0;
Buf[i].UserTime = 0;
Buf[i].Handle = 0;
}
}
And the destructor:
TBuffer::~TBuffer()
{
DeleteCriticalSection(&cs);
}
The method using critical section:
void TBuffer::Set(int Id, const TProcessInfo Pi)
{
EnterCriticalSection(&cs);
...
LeaveCriticalSection(&cs);
}
In the main .cpp
file, I have a global variable:
TBuffer *Buffer;
And in the MainWndProc
function where messages are processed, in the case WM_INITDIALOG
I am asked to create a TBuffer
class object to initialize the critical section and so on:
case WM_INITDIALOG:
{
TBuffer Buf(hWnd);
Buffer = &Buf;
...
return TRUE;
}
My problem is that, as I read, the class object after return TRUE
is going out of scope and its destructor is called. That's why the critical section is deleted and then other class methods like Set()
and Get()
are not able to enter the critical section. So I'm looking for a way to leave the object in scope. I think that something is wrong in WM_INITDIALOG
with object creation.
By the way, when the WM_DESTROY
message is processed, I free the allocated memory for the global variable:
case WM_DESTROY:
delete[] Buffer;
PostQuitMessage(0);
return TRUE;