In my .h file function mouseProc is declared as static(it has to be)
.h file
static LRESULT CALLBACK mouseProc(int Code, WPARAM wParam, LPARAM lParam);
initially i thought i would add &ui as a parameter to this function, but i am not able to do so. it gives me error "incompatible parameter type with HOOKPROC"
so, now i am not able to access the textboxes and labels in my UI by using
ui->textbox->apped(); how to solve this ?
---UPDATE as per suggestion of making ui static--------------
mainwindow.h
#pragma once
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "windows.h"
#include "windowsx.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT //Used to handle events
Q_DISABLE_COPY(MainWindow) //added
public:
MainWindow(QWidget* parent = 0);
~MainWindow(); //Destructor used to free resources
// Static method that will act as a callback-function
static LRESULT CALLBACK mouseProc(int Code, WPARAM wParam, LPARAM lParam);
// BOOL InitializeUIAutomation(IUIAutomation** automation);
static Ui::MainWindow* ui; // declared static,pointing to UI class
private:
// hook handler
HHOOK mouseHook;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <Windows.h>
#include <UIAutomation.h>
using namespace std;
Ui::MainWindow* MainWindow::ui = 0;
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
//, ui(new Ui::MainWindow)
{
ui = new Ui::MainWindow();
ui->setupUi(this);
HINSTANCE hInstance = GetModuleHandle(NULL);
// Set hook
mouseHook = SetWindowsHookEx(WH_MOUSE_LL, &mouseProc, hInstance, 0);
// Check hook is correctly
if (mouseHook == NULL)
{
qWarning() << "Mouse Hook failed";
}
}
BOOL InitializeUIAutomation(IUIAutomation** automation)
{
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(__uuidof(CUIAutomation), NULL,
CLSCTX_INPROC_SERVER, __uuidof(IUIAutomation),
(void**)automation);
return (SUCCEEDED(hr));
}
MainWindow::~MainWindow()
{
delete ui;
}
LRESULT CALLBACK MainWindow::mouseProc(int Code, WPARAM wParam, LPARAM lParam)
{
ui->textbox->append(string);
}
You can't add extra parameters to mouseProc. The compiler won't accept it, it needs to match the signature that SetWindowsHookEx() is expecting. If you resort to using a type-cast to force the compiler to accept it, the OS still won't know how to populate the new parameters with values at runtime when the hook is called, and you will just end up corrupting the call stack, and/or crashing your code.
To do what you want, you will simply have to store your ui pointer in global memory, or even make it be static as well. Somewhere that mouseProc can reach it.
As for the compiler error, what it says is correct - the MainWindow class you have shown does not have a member named textbox, which is why accessing ui->textbox (regardless of where ui will come from) fails to compile. So, you need to figure out where the textbox is really being stored, and then access it from THERE instead of from the MainWindow.
Related
I've been racking my brain on this for days, and could use some help! I'm able to detect a CBT hook using SetWindowsHookEx when it is hooked to the thread ID of my WPF application, but I'm not able to get it to hook to the Thread ID of another process window when that window becomes the foreground app.
Image 1: Shows that I CAN get the CBT hook for detecting window maximize on the main app's Thread ID
Image 2: Shows that I CANNOT get the CBT hook when listening to another app's Thread ID, and it will crash the app!
I want to avoid sending ThreadId=0 and making it a complete global hook, because I know that I only want to listen to the foreground app, not all apps on the desktop. I want to be able to listen to a few window events before they happen (WH_CBT does this from what I understand) for any window that currently has the foreground focus.
Again, the following code works when the current WPF app becomes the foreground app, but it fails when another app's window becomes the foreground (e.g. Notepad, Internet Explorer, File Explorer, Chrome, etc.).
Full Code: (link to github zip file)
Here are some snippets of the code to show what I did:
DLL that defines the callback (inject.dll):
inject.h: Snippet
typedef void(__stdcall* MYFUNCPTR)(int code, WPARAM wparam, LPARAM lparam);
extern "C" __declspec(dllexport) void Init(MYFUNCPTR funcPtr);
extern "C" __declspec(dllexport) LRESULT CALLBACK CbtProcCallback(int code, WPARAM wparam, LPARAM lparam);
WPARAM wparam, LPARAM lparam);
MYFUNCPTR _handler = 0;
inject.cpp: Snippet
void Init(MYFUNCPTR funcPtr)
{
_handler = funcPtr;
}
LRESULT CALLBACK CbtProcCallback(int code, WPARAM wparam, LPARAM lparam)
{
if (code >= 0)
{
// Only send the code if you are about to MAXIMIZE
if (code == HCBT_MINMAX)
{
if (lparam == SW_MAXIMIZE)
{
_handler(0, wparam, lparam);
}
}
}
return CallNextHookEx(NULL, code, wparam, lparam);
}
DLL that sets the CBT hook (dllwrapper.dll):
dllwrapper.cpp: Snippet
// Load library in which we'll be hooking our functions.
HMODULE dll = LoadLibrary(L"inject.dll");
if (dll == NULL) {
char errorMessage[100];
sprintf_s(errorMessage, "ERR-LoadLibrary failed! ErrorCode=%d", GetLastError());
SendManagedMessage(errorMessage);
return false;
}
SendManagedMessage("LoadLibrary passed!");
// Get the address of the function inside the DLL.
MYPROC iaddr = (MYPROC)GetProcAddress(dll, "Init");
if (iaddr == NULL) {
char errorMessage[100];
sprintf_s(errorMessage, "ERR-GetProcAddress for Init failed! ErrorCode=%d", GetLastError());
SendManagedMessage(errorMessage);
return false;
}
SendManagedMessage("GetProcAddress for Init passed!");
iaddr(OnInjectionCallback);
// Get the address of the function inside the DLL.
HOOKPROC cbtProcAddress = (HOOKPROC)GetProcAddress(dll, "CbtProcCallback");
if (cbtProcAddress == NULL) {
char errorMessage[100];
sprintf_s(errorMessage, "ERR-GetProcAddress for CbtProcCallback failed! ErrorCode=%d", GetLastError());
SendManagedMessage(errorMessage);
return false;
}
SendManagedMessage("GetProcAddress for CbtProcCallback passed!");
// Hook the function
cbtProcHook = SetWindowsHookEx(WH_CBT, cbtProcAddress, dll, _threadId);
if (cbtProcHook == NULL) {
char errorMessage[100];
sprintf_s(errorMessage, "ERR-SetWindowsHookEx cbtProcAddress failed! ErrorCode=%d", GetLastError());
SendManagedMessage(errorMessage);
return false;
}
SendManagedMessage("SetWindowsHookEx for cbtProcAddress passed!");
Snippet exporting to C#
typedef void(__stdcall* CodeCallback)(int code, WPARAM wparam, LPARAM lparam);
typedef void(__stdcall* MessageCallback)(const char* message);
#ifdef __cplusplus
extern "C" { // only need to export C interface if
// used by C++ source code
#endif
__declspec(dllexport) bool StartHooks(unsigned int threadId, MessageCallback messageCallback, CodeCallback codeCallback);
__declspec(dllexport) void StopHooks();
#ifdef __cplusplus
}
#endif
NativeMethods.cs: Snippet of C# dll imports to the WPF app
public delegate void MessageCallback(string message);
public delegate void CodeCallback(int code, IntPtr wParam, IntPtr lParam);
[DllImport("dllwrapper.dll")]
public extern static bool StartHooks(uint threadId, MessageCallback messageHandler, CodeCallback codeHandler);
[DllImport("dllwrapper.dll")]
public extern static void StopHooks();
I can see from the messages in the WPF app window that the hook is passing and not returning any Win32 errors, but it's just not executing the callback when another window has focus (even when using the debugger).
Any help would be greatly appreciated!
Development Environment:
Windows 10 1909
VS2019 16.7.4
C# .NET Framework 4.7.2, C++
When the main app calls Init(), it is calling into its own instance of the DLL, and so is setting its own copy of _handler.
When your hook DLL is injected into another process, that process will get its own copy of the DLL, and thus its own copy of _handler. But Init() is never called on that DLL instance, so its copy of _handler is still 0 when your hook function is invoked inside that process. That is why the process crashes, since the hook is not checking for that condition.
Your DLL in another process can't call a function in your main app across process boundaries. You are going to have to change your hook function to instead use an IPC mechanism of your choosing to communicate with the main app process when _handler is 0. Window messages, pipes, mailslots, sockets, etc can be used for that communication.
I build the code successfully but it does not debug and comes up with this warning in a wizard miscellaneous code.
"Warning: Destroying non-NULL m_pMainWnd\n"
and
"Warning: Temp map lock count non-zero (%ld).\n",
The aim of this is to create a dialog box that allows a user to input car specifications and a track so a lap time can be calculated.
Source File of Main Dialogue box:
#define _WIN32_WINNT 0x0601
// LapTimeSim.cpp : implementation file
//
#include <iostream>
#include "stdafx.h"
#include "LapTimeSim.h"
#include "afxdialogex.h"
#include "SecondDlg.h"
#include "resource.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
using namespace std;
// LapTimeSim dialog
IMPLEMENT_DYNAMIC(LapTimeSim, CDialogEx);
LapTimeSim::LapTimeSim(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_DIALOG1, pParent)
{
}
LapTimeSim::~LapTimeSim()
{
}
void LapTimeSim::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(LapTimeSim, CDialogEx)
ON_BN_CLICKED(IDC_CAR, &LapTimeSim::OnBnClickedCar)
ON_BN_CLICKED(IDGO, &LapTimeSim::OnBnClickedGo)
ON_BN_CLICKED(IDC_TRACK, &LapTimeSim::OnBnClickedTrack)
END_MESSAGE_MAP()
// LapTimeSim message handlers
void LapTimeSim::OnBnClickedCar()
{
// TODO: Add your control notification handler code here
CSecondDlg Dlg;
Dlg.DoModal();
}
void LapTimeSim::OnBnClickedGo()
{
// TODO: Add your control notification handler code here
}
void LapTimeSim::OnBnClickedTrack()
{
// TODO: Add your control notification handler code here
}
A Large Header; Header file of main dialog box
==============
#pragma once
// LapTimeSim dialog
class LapTimeSim : public CDialogEx
{
DECLARE_DYNAMIC(LapTimeSim)
public:
LapTimeSim(CWnd* pParent = NULL); // standard constructor
virtual ~LapTimeSim();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOG1 };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedCar();
afx_msg void OnBnClickedGo();
afx_msg void OnBnClickedTrack();
};
Source File of Main Dialogue box:
// SecondDlg.cpp : implementation file
//
#define _WIN32_WINNT 0x0601
#include <iostream>
#include "stdafx.h"
#include "LapTimeSim.h"
#include "afxdialogex.h"
#include "SecondDlg.h"
#include "resource.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CSecondDlg dialog
IMPLEMENT_DYNAMIC(CSecondDlg, CDialog)
CSecondDlg::CSecondDlg(CWnd* pParent /*=NULL*/)
: CDialog(IDD_DIALOG2, pParent)
{
}
CSecondDlg::~CSecondDlg()
{
}
void CSecondDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CSecondDlg, CDialog)
END_MESSAGE_MAP()
// CSecondDlg message handlers
A Large Header; Header file of second dialog box
==============
#pragma once
// CSecondDlg dialog
class CSecondDlg : public CDialog
{
DECLARE_DYNAMIC(CSecondDlg)
public:
CSecondDlg(CWnd* pParent = NULL); // standard constructor
virtual ~CSecondDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOG2 };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
};
Source File : appmodule.cpp writeen by the wizard
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "sal.h"
/////////////////////////////////////////////////////////////////////////////
// export WinMain to force linkage to this module
extern int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine, int nCmdShow);
extern "C" int WINAPI
_tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine, int nCmdShow)
#pragma warning(suppress: 4985)
{
// call shared/exported WinMain
return AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
}
/////////////////////////////////////////////////////////////////////////////
// initialize app state such that it points to this module's core state
BOOL AFXAPI AfxInitialize(BOOL bDLL, DWORD dwVersion)
{
AFX_MODULE_STATE* pModuleState = AfxGetModuleState();
pModuleState->m_bDLL = (BYTE)bDLL;
ASSERT(dwVersion <= _MFC_VER);
UNUSED(dwVersion); // not used in release build
#ifdef _AFXDLL
pModuleState->m_dwVersion = dwVersion;
#endif
#ifdef _MBCS
// set correct multi-byte code-page for Win32 apps
if (!bDLL)
_setmbcp(_MB_CP_ANSI);
#endif //_MBCS
return TRUE;
}
// force initialization early
#pragma warning(disable: 4074)
#pragma init_seg(lib)
#ifndef _AFXDLL
void AFX_CDECL _AfxTermAppState()
{
// terminate local data and critical sections
AfxTermLocalData(NULL, TRUE);
AfxCriticalTerm();
// release the reference to thread local storage data
AfxTlsRelease();
}
#endif
#ifndef _AFXDLL
char _afxInitAppState = (char)(AfxInitialize(FALSE, _MFC_VER), atexit(&_AfxTermAppState));
#else
char _afxInitAppState = (char)(AfxInitialize(FALSE, _MFC_VER));
#endif
/////////////////////////////////////////////////////////////////////////////
Source File - Wizard code coming up with warning:
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "sal.h"
/////////////////////////////////////////////////////////////////////////////
// Standard WinMain implementation
// Can be replaced as long as 'AfxWinInit' is called first
int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine, int nCmdShow)
{
ASSERT(hPrevInstance == NULL);
int nReturnCode = -1;
CWinThread* pThread = AfxGetThread();
CWinApp* pApp = AfxGetApp();
// AFX internal initialization
if (!AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nCmdShow))
goto InitFailure;
// App global initializations (rare)
if (pApp != NULL && !pApp->InitApplication())
goto InitFailure;
// Perform specific initializations
if (!pThread->InitInstance())
{
if (pThread->m_pMainWnd != NULL)
{
TRACE(traceAppMsg, 0, "Warning: Destroying non-NULL m_pMainWnd\n");
pThread->m_pMainWnd->DestroyWindow();
}
nReturnCode = pThread->ExitInstance();
goto InitFailure;
}
nReturnCode = pThread->Run();
InitFailure:
#ifdef _DEBUG
// Check for missing AfxLockTempMap calls
if (AfxGetModuleThreadState()->m_nTempMapLock != 0)
{
TRACE(traceAppMsg, 0, "Warning: Temp map lock count non-zero (%ld).\n",
AfxGetModuleThreadState()->m_nTempMapLock);
}
AfxLockTempMaps();
AfxUnlockTempMaps(-1);
#endif
AfxWinTerm();
return nReturnCode;
}
/////////////////////////////////////////////////////////////////////////////
(See my answer to this SO: Cannot create main window?, it looks very similar to your issue)
If you have created this project with wizard then you should also have source files for CWinApp implementation. If its some other kind of wizard generated application then you still should somewhere have an InitInstance like method. with following lines of code:
LapTimeSim dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
(I assume here that LapTimeSim is your main entry dialog). If you remove above lines, you will get the exact same trace and behaviour as in your description (I checked this locally).
So you should check if you have by mistake removed them, or recreate project from MFC template wizard.
I have this code:
void CALLBACK CTestTimeUpDlg::MyTimerProc(
HWND hWnd, // handle of CWnd that called SetTimer
UINT nMsg, // WM_TIMER
UINT_PTR nIDEvent, // timer identification
DWORD dwTime // system time
)
{
const int m_TimerValue=0;
double timeValueSec=m_TimerValue/1000.0;
CString valueString;
valueString.Format(L"%3.3f",timeValueSec);
m_TimerDisplayValue.SetWindowTextW(valueString);
}
void CTestTimeUpDlg::OnBnClickedButtonStart()
{
m_TimerValue=0;
m_Timer = SetTimer(1, 1, &CTestTimeUpDlg::MyTimerProc);
}
but when I compiled it, I am getting this error:
'CWnd::SetTimer' : cannot convert parameter 3 from 'void (__stdcall CTestTimeUpDlg::* )(HWND,UINT,UINT_PTR,DWORD)' to 'void (__stdcall *)(HWND,UINT,UINT_PTR,DWORD)'
the code is similar to the code from Microsoft documentation:
http://msdn.microsoft.com/en-us/library/49313fdf.aspx
You should make CTestTimeUpDlg::MyTimerProc static. However, by doing this, you can't access instance members such as m_TimerDisplayValue.
You shouldn't use callback in this case. Set lpfnTimer NULL, as the first timer in the sample of the link. That way, the timer posts the message WM_TIMER, and you can handle it by your non-static member function.
ADD:
Seems the document (plus my words above) is lacking in explanation.
Do as followings to implement a handler of WM_TIMER.
Declare handler in your class declaration:
afx_msg void OnTimer(UINT_PTR nIDEvent);
In your cpp file, add message mapping:
BEGIN_MESSAGE_MAP(CTestTimeUpDlg, ...)
ON_WM_TIMER()
END_MESSAGE_MAP()
and implementation:
void CTestTimeUpDlg::OnTimer(UINT_PTR nIDEvent)
{
// your code here...
}
i created a MFC dialog application.
now i want to use a messageloop, but i can not find it. I read that mfc will create it for me but that it will be hidden. so how can i manipulate the messageloop?
i need the messageloop to recieve events from my tray icon which i created for that application.
so that i can use something like that:
long CALLBACK WndProc(HWND hWnd, UINT nMsg, UINT wParam, LONG lParam)
{
switch(nMsg)
{
case (WM_USER + 1):
{
switch(lParam)
{
case WM_RBUTTONUP:
{
/**/
}
}
return 0;
}
default:
return DefWindowProc(hWnd, nMsg, wParam, lParam);
}
}
I'm still a beginner at mfc.
After installing an icon to the system tray by Shell_NotifyIcon, this icon become the extension of your dialog UI. When the user interact with this icon, the UI messages will be re-directed to your dialog by the OS automatically.
To serve these user messages you needs to perform few steps:
(1) Add a message handler definition (ON_MESSAGE(WM_TRAY_NOTIFY, OnTrayNotify)) inside the (.cpp) file. Must be inside the BEGIN_MESSAGE_MAP/END_MESSAGE_MAP block:
BEGIN_MESSAGE_MAP(CTestDlg, CDialog)
//{{AFX_MSG_MAP(CTestDlg)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
...
//}}AFX_MSG_MAP
ON_MESSAGE(WM_TRAY_NOTIFY, OnTrayNotify)
END_MESSAGE_MAP()
(2) Add a message handler implementation in the (.cpp) file, to perform the actual work
void CTestDlg::OnTrayNotify(UINT nID, LPARAM lEvent)
{
if (nID==TRAYICON_ID1)
{
// handle messages here
if (lEvent==WM_LBUTTONDBLCLK)
{ // do left button double click, usually restore application
}
if (lEvent==WM_RBUTTONUP)
{ // do right button up, usually popup a menu at clicked location
}
}
}
(3) Add a prototype definition of this message handler (afx_msg void OnTrayNotify(UINT nID, LPARAM lEvent);) inside the (.h) file. Must be inside the BEGIN_MESSAGE_MAP/END_MESSAGE_MAP block:
// Generated message map functions
//{{AFX_MSG(CTestDlg)
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
...
//}}AFX_MSG
afx_msg void OnTrayNotify(UINT nID, LPARAM lEvent);
DECLARE_MESSAGE_MAP()
(4) Add definition inside (.h) file
#define WM_TRAY_NOTIFY WM_USER+567
#define TRAYICON_ID1 0x1234
The code above is assuming:
The dialog name is CTestDlg, change it to your dialog name
The user-callback-message identifier (uCallbackMessage) used to setup Shell_NotifyIcon is WM_TRAY_NOTIFY
The identifier of the tray icon (uID) sed to setup Shell_NotifyIcon is TRAYICON_ID1
For a Windows application I'm trying to get CreateWindow() and WndProc() (or my versions of them) to be part of a singleton class that is created at the beginning of _tWinMain() but since trying to shift the functions to GameHandler.h and GameHandler.cpp I keep getting "unresolved external symbol _WinMain#16". They were originally global functions in main.cpp and everything was compiling fine then I decided to move them to GameHandler and ever since all I get is the unresolved external, even if I try to move them back to main.cpp.
I'm doing this in VS2010, the project was created as a Windows Application and there's no specific entry point set in properties (I double checked as every solution I've found so far says that it's because it's a console app - this isn't).
The code I currently have is shown below. The actual project has a couple of thousand lines of other code that I've left out as I don't think it's relevant (but will happily proved wrong. While the actual window creation code is related, I don't think the code itself is the problem (apart from what I left in), it's the location of GameWindowProc() &/or CreateGameWindow() or how they're called. The actual window creation code is taken from NeHe's tutorial. Trying to compile the following code only gives the aforementioned unresolved external.
main.cpp:
#include <Windows.h>
#include "GameManager.h"
#ifndef USEGMGR
bool CreateGameWindow(char* title, int width, int height, int bits, bool fullScreenFlag);
LRESULT CALLBACK GameWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
#endif
int APIENTRY _tWinMain(HINSTANCE hInst, HINSTANCE hPrevInst,
LPTSTR lpCmdLine, int nCmdShow)
{
GameManager::Startup();
GameManager* GMgr = GameManager::GetInstance();
GMgr->SetProgramState(GAME_MODE);
while(GMgr->GetProgramState() != GAME_MODE) // Normally this would be if (State != GAME_QUIT)
{ /* do game related stuff */ }
GameManager::Shutdown();
return 0;
}
#ifndef USEGMGR
bool CreateGameWindow(char* title, int width, int height, int bits, bool fullScreenFlag)
{
// Fairly complex but flexible creation code, taken from NeHe's tutorials. Of relevant interest is:
WNDCLASS wc; // Windows Class Structure
wc.lpfnWndProc = (WNDPROC) GameWindowProc; // WndProc Handles Messages
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return false;
}
return true;
}
LRESULT CALLBACK GameWindowProc(HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
// various custom message handling, if not processed:
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
#endif
in GameManager.h:
#ifndef GAMEMANAGER_H
#define GAMEMANAGER_H
#define USEGMGR // makes CreateGameWindow() and GameWindowProc() methods in GameManager instead of global
#include <Windows.h>
enum ProgramState
{
GAME_MODE,
GAME_QUIT,
};
class GameManager
{
public:
static void Startup();
static void Shutdown();
static GameManager* GetInstance();
void Update(); // code not shown, check quit key etc
#ifdef USEGMGR
const bool CreateGameWindow(char* title, int width, int height, int bits, bool fullScreenFlag);
static LRESULT CALLBACK GameWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
#endif
void KillGameWindow(void);
const int GetProgramState() const;
void SetProgramState(const int& newMode);
private:
GameManager();
~GameManager();
GameManager(const GameManager&);
GameManager& operator=(const GameManager&);
HINSTANCE m_hInstance;
HWND m_hWnd;
HDC m_hDC;
static GameManager* s_instance;
int m_programState; // uses ProgramState enum
};
#endif
in GameManager.cpp:
#include "GameManager.h"
#include <Windows.h>
#include <assert.h>
#ifndef USEGMGR
extern bool CreateGameWindow(char* title, int width, int height, int bits, bool fullScreenFlag);
#endif
GameManager* GameManager::s_instance = NULL;
GameManager::GameManager(){}
GameManager::~GameManager(){}
void GameManager::Startup()
{
assert(s_instance == NULL);
s_instance = new GameManager;
#ifdef USEGMGR
if (! (s_instance->CreateGameWindow("Game Window", 800, 600, 32, true )) )
#else
if (! (CreateGameWindow("Game Window", 800, 600, 32, true )) )
#endif
assert("CreateGameWindow failed! Need an error here"); // Quit If Window Was Not Created - clean this up later
}
void GameManager::Shutdown()
{
assert(s_instance != NULL);
delete s_instance;
s_instance = NULL;
}
GameManager* GameManager::GetInstance(){return s_instance;}
void GameManager::Update(){/* msg handling, watch for quit key, etc */}
const int GameManager::GetProgramState() const{return s_instance->m_programState;}
void GameManager::SetProgramState(const int& newState){s_instance->m_programState = newState;}
#ifdef USEGMGR
const bool GameManager::CreateGameWindow(char* title, int width, int height, int bits, bool fullScreenFlag)
{
// Fairly complex but flexible creation code, taken from NeHe's tutorials. Of relevant interest is:
WNDCLASS wc; // Windows Class Structure
wc.lpfnWndProc = (WNDPROC) GameManager::GameWindowProc; // WndProc Handles Messages
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return false;
}
return true;
}
LRESULT CALLBACK GameManager::GameWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
// various custom message handling, if not processed:
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
#endif
As you can see, I've set up some preprocessor conditionals to switch between the troublesome functions being in main.cpp or as part of GameManager. Comment out #define USEGMGR at the beginning of GameManager.h to have them as global funcs in main.cpp.
Can someone please tell me what I'm doing wrong?
Edit: removed comment about not being able to quit if you get it to run.
The WinMain function cannot be a member function of a class, even a "singleton" class.
Since it functions as the "entry point" for the program, essentially replacing the main function you'd find in a traditional C++ application, it needs to be a free global function.
The message Unresolved external _WinMain#16 is simply the compiler's cryptic way of telling you that it cannot locate the expected entry point, named WinMain (plus some name mangling).
Add
#include <tchar.h>
to the top of main.cpp so that the _tWinMain macro gets defined properly.
What happens if you don't have the macro definition is that you end up with a function named _tWinMain() (or some mangled version of the name like ?_tWinMain##YGHPAUHINSTANCE__##0PADH#Z()) in the object file, but the linker and runtime initialization code are looking for WinMain() or wWinMain(). They don't find it.
<tchar.h> defines a macro that transforms the name _tWinMain() into one of the two names everything else is looking for. You must have had something including that header before you started your refactoring (quite possibly indirectly), and lost it somehow.
Or you can dispense with the macro version and name the function WinMain or wWinMain (either one should work, regardless of whether you're building for UNICODE or not). If you do that, just remember to change the LPTSTR parameter declaration to match the one you choose.