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;
	bool rv = (::WaitForSingleObject(_threadHandle, timeOut) == WAIT_OBJECT_0);
	if (rv) CloseHandle(_threadHandle);
	return rv;
}

// メッセージを送る
bool BaseProcess::Tell(ECTMSG msg, WPARAM wp, LPARAM lp) {
	if (!_messageQueReady || !_threadID) return false;	// メッセージキューの準備確認
	::PostThreadMessage(_threadID, (int)msg, wp, lp);
	return true;
}