feat(*): add log file and message loop

This commit is contained in:
2025-06-21 20:23:05 +08:00
parent 195ef20854
commit a9f963dc6c
2 changed files with 212 additions and 7 deletions

View File

@ -1,28 +1,104 @@
#include <windows.h>
#include "Defines.h"
#include <windows.h>
#include <iostream>
#include <fstream>
#include <thread>
#include <chrono>
#include <string>
#include <filesystem>
#include <ctime>
#include <iomanip>
#include <mutex>
#pragma warning(disable: 4996)
// ReSharper disable CppDeprecatedEntity
// ReSharper disable CppClangTidyCertErr33C
std::ofstream GLogFile;
void PrintLog(const std::string& Text)
{
const auto Now = std::chrono::system_clock::now();
const auto Time = std::chrono::system_clock::to_time_t(Now);
const long long Milliseconds = (std::chrono::duration_cast<std::chrono::milliseconds>(Now.time_since_epoch()) % 1000).count();
static std::mutex Mutex; std::lock_guard Lock(Mutex);
const std::tm* LocalTime = std::localtime(&Time); // NOLINT(concurrency-mt-unsafe)
char Buffer[] = "[2025-06-21 20:05:04.305]: ";
std::strftime(&Buffer[1], 20, "%Y-%m-%d %H:%M:%S", LocalTime);
Buffer[20] = '.';
constexpr char Digits[] = "0123456789";
Buffer[21] = Digits[Milliseconds / 100 % 10];
Buffer[22] = Digits[Milliseconds / 10 % 10];
Buffer[23] = Digits[Milliseconds / 1 % 10];
GLogFile << Buffer << Text << std::endl;
}
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
using namespace std::chrono_literals;
AllocConsole();
const HANDLE Mutex = CreateMutex(nullptr, TRUE, "FocusIME_SingleInstance_Mutex");
freopen("CONOUT$", "w", stdout);
if (Mutex == nullptr)
{
MessageBox(nullptr, "Failed to create mutex.", "FocusIME", MB_OK | MB_ICONERROR);
SetConsoleTitle("FocusIME");
return 1;
}
std::cout << "Hello, FocusIME!" << std::endl;
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
MessageBox(nullptr, "FocusIME is already running.", "FocusIME", MB_OK | MB_ICONINFORMATION);
std::this_thread::sleep_for(3s);
CloseHandle(Mutex);
FreeConsole();
return 0;
}
GLogFile.open("Log.txt", std::ios::out | std::ios::app);
if (!GLogFile.is_open())
{
MessageBox(nullptr, "Failed to open log file.", "FocusIME", MB_OK | MB_ICONERROR);
CloseHandle(Mutex);
return 1;
}
PrintLog("FocusIME started successfully");
MSG Message = { };
while (true)
{
BOOL bResult = GetMessage(&Message, nullptr, 0, 0);
if (bResult > 0)
{
TranslateMessage(&Message);
DispatchMessage (&Message);
}
else break;
}
PrintLog("FocusIME is shutting down...");
GLogFile.close();
CloseHandle(Mutex);
return 0;
}