Newer
Older
PrismSoftware / ECTrainer2 / BaseProcess.cpp
#include "BaseProcess.h"
#include "ECTrainer.h"
#include "MyWinUtils.h"

// コンストラクタ
BaseProcess::BaseProcess(ECTrainer* pEct) 
	: _pEct(pEct) 
	, _messageQueReady(false)
	, _threadHandle(NULL)
	, _threadID(0)
{
}

// スレッド起動
bool BaseProcess::Launch() {
	_threadHandle = ::CreateThread(NULL, 0, ThreadEntry, this, 0, &_threadID);
	return true;
}

// 初期化
bool BaseProcess::Init() {
	return true;
}

// スレッド本体
bool BaseProcess::MainLoop() {
	if (_threadID == 0) _threadID = ::GetCurrentThreadId();	// メインスレッドID取得
	mwut::DebugPrintf(_T("Thread %d start\n"), _threadID);

	// メッセージキューの作成
	MSG msg;
	::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
	_messageQueReady = true;

	// ループ
	while (1) {
		if (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
			if (!::GetMessage(&msg, NULL, 0, 0)) break;
			if (!this->EventProc(msg)) break;
		} else {
			if (!this->Routine()) break;
		}
	}
	return true;
}

// 非メッセージ時の処理
bool BaseProcess::Routine() {

	return true;
}

// メッセージ処理
bool BaseProcess::EventProc(MSG &msg) {
	mwut::DebugPrintf(_T("Receive Th %d msg %d\n"), _threadID, msg.message);

	return true;
}

// スレッド起動点
DWORD WINAPI BaseProcess::ThreadEntry(LPVOID lpParameter) {
	if (!((BaseProcess*)lpParameter)->MainLoop()) return 1;
	return 0;
}

// スレッド終了待ち
bool BaseProcess::WaitForExit(DWORD timeOut) {
	if (!_threadHandle) return false;
	DWORD rv = ::WaitForSingleObject(_threadHandle, timeOut);
	return (rv == WAIT_OBJECT_0);
}

// メッセージを送る
bool BaseProcess::Tell(int msgid) {
	if (!_messageQueReady || !_threadID) return false;	// メッセージキューの準備確認
	if (::GetCurrentThreadId() == _threadID) ::PostQuitMessage(0);
	else 		::PostThreadMessage(_threadID, msgid, 0, 0);
	return true;
}

// スレッドハンドルを閉じる
void BaseProcess::CloseThread() {
	CloseHandle(_threadHandle);
}