In Win32 API a window has the pointer to a user defined version of WndProc function that handling its messages.
There are some ways to cover this low-level mechanism with a solution like MFC message map and so on.
In my very little app I'm looking for a way to encapsulate this low-level thing with a object oriented solution.
I tried to create a C++ map with HWND key and "MyWindowClass" item and when I created an object of the MyClass I added a pair to the map and then looking for the MyWindowClass object by HWN. But the problem is after CreateWindowEx called Win32 internally send a WM_CREATE message to the just created window so I can't add pair in the map before this message and can't control WM_CREATE through passing it to the object instanced WndProc.
The code is:
#ifndef NOTIFYWINDOW_H
#define NOTIFYWINDOW_H
#include "Bacn.h"
class NotifyWindow
{
private:
HWND m_hWnd;
Gdiplus::Graphics* m_graphics;
protected:
static std::map<HWND, NotifyWindow*> s_NotifyWindows;
static LRESULT CALLBACK s_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static void s_WndMessageLoop();
LRESULT WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
void Initialize();
void OnPaint();
void OnCreate();
public:
NotifyWindow();
~NotifyWindow();
};
#endif //NOTIFYWINDOW_H
And its implementation:
#include "NotifyWindow.h"
using namespace Gdiplus;
using namespace std;
map<HWND*, NotifyWindow> NotifyWindow::s_NotifyWindows;
LRESULT CALLBACK NotifyWindow::s_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
map<HWND, NotifyWindow*>::iterator search = s_NotifyWindows.find(hWnd);
if (search != s_NotifyWindows.end())
{
search->second->WndProc(uMsg, wParam, lParam);
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
void NotifyWindow::s_WndMessageLoop()
{
}
LRESULT NotifyWindow::WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CREATE:
OnCreate();
break;
case WM_PAINT:
OnPaint();
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_SIZE:
break;
case WM_SETFOCUS:
break;
case WM_KILLFOCUS:
break;
case WM_MOUSEMOVE:
break;
default:
return DefWindowProc(m_hWnd, uMsg, wParam, lParam);
}
return 0;
}
void NotifyWindow::Initialize()
{
WNDCLASSEX wc;
const wchar_t *className = L"BacnNotifyWindowClass";
const wchar_t *windowName = L"BacnNotifyWindow";
HINSTANCE hInstance = GetModuleHandle(NULL);
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpszClassName = className;
wc.lpfnWndProc = NotifyWindow::s_WndProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = NULL;
wc.hIconSm = NULL;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
RegisterClassEx(&wc);
DWORD dwExtStyle = WS_EX_TOPMOST;
DWORD dwStyle = WS_POPUP | WS_SYSMENU;
m_hWnd = CreateWindowEx(
dwExtStyle,
className,
windowName,
dwStyle,
300,
300,
100,
100,
NULL,
NULL,
hInstance,
NULL);
s_NotifyWindows.insert(pair<HWND, NotifyWindow*>(m_hWnd, this));
ShowWindow(m_hWnd, SW_SHOW);
}
NotifyWindow::NotifyWindow()
{
Initialize();
}
NotifyWindow::~NotifyWindow()
{
}
void NotifyWindow::OnPaint()
{
}
void NotifyWindow::OnCreate()
{
}
Suggestion: make WndProc virtual in your window base class. Request Windows to allocate extra memory for each window instance big enough to store a pointer (use cbWndExtra). When creating a window, put a pointer to your windows class object into this extra memory associated with each window instance using SetWindowLongPtr. In your static sWndProc, retrieve this pointer using GetWindowLongPtr and call your window base class function virtual WndProc. In my opinion, it's more neat way than having a whole extra map object dedicated to dispatching WndProc calls.
EDIT: Plus, you do realize, in your code you are trying to register Windows window class every time you create an object of your window class? If you create just one window this is technically fine, I guess, but even then it's error-prone design. Windows window class should be registered just once, not every time you create a window with this Windows window class.
EDIT: Also, in your code, if you are not processing Windows message in your WndProc, you code will call DefWindowProc twice for this message: first time in member function within switch clause, second time in static sWndProc. DefWindowProc shouldn't be called twice on the same message.
EDIT: Sorry, I missed your actual question before somehow, I thought your post was about design, not about WM_CREATE. In order to process WM_NCCREATE, WM_NCCALCSIZE or WM_CREATE in a uniform way, you can set lpParam in call to CreateWindowEx to, again, pointer to the object of your window class. This parameter will be passed to your static sWndProc as a member of CREATESTRUCT with WM_NCCREATE and WM_CREATE. You can process, say, WM_NCCREATE (first message to be sent) inside static sWndProc, get this pointer to your object, use SetWindowLongPtr to put it into window instance extra memory, and then use it to call member function WndProc (just be careful about calling not fully created object of your windows class, if you call CreateWindowEx from its constructor). This way, you don't need to worry about "low-level" Windows message dispatching anywhere else in your program. You, of course, will still need your member function WndProc to dispatch messages to actual function calls.
Related
I have been working with C++ and Win32 (non MFC/ATL) I am playing around with writing my own class library to wrap certain Win32 objects (HWNDs in particular).
When it comes to creating windows, I find the "RegisterClassEx / CreateWindowEx" method very awkward. This design makes it hard to write simple class wrappers (one must resort to thunks, or TLS or some other complicated mechanism).
It seems to me it would have been simpler to just let the application specify the window procedure and a user-data pointer at window creation time.
Is there any obvious reason I'm missing for the design choice here? Is there a really simple and efficient way for this to work?
ATL's CWindow and CWindowImpl are your friends.
CWindowImpl makes takes care of the RegisterClass/CreateWindow awkwardness that you speak of.
CWindow is a basic "wrapper" class for an HWND with all the win32 functions abstracted out.
The reason I prefer ATL over MFC. ATL is a very lightweight set of classes with all the source code provided. It's a simple #include with no extra libraries or runtimes to deal with. After rolling my own WndProcs and window encapsulation classes for many years, I've found CWindowImpl a joy to work with. You have to declare a global AtlModuleExe instance in your code to use it, but besides that, ATL stays out of the way.
Links to documenation for these classes below:
CWindow:
http://msdn.microsoft.com/en-us/library/d19y607d.aspx
CWindowImpl:
http://msdn.microsoft.com/en-us/library/h4616bh2.aspx
Update: Here's some sample code I dug up for you:
class CMyApp : public CAtlExeModuleT<CMyApp>
{
public:
static HRESULT InitializeCom()
{
CoInitialize(NULL);
return S_OK;
}
};
CMyApp g_app;
class CMyWindow : public CWindowImpl<CMyWindow>
{
public:
CMyWindow();
~CMyWindow();
BEGIN_MSG_MAP(CMyWindow)
MESSAGE_HANDLER(WM_PAINT, OnPaint);
MESSAGE_HANDLER(WM_CLOSE, OnClose);
END_MSG_MAP();
LRESULT OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
};
LRESULT CMyWindow::OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled)
{
// your WM_PAINT code goes here
}
LRESULT CMyWindow::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled)
{
PostQuitMessage();
}
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdline, int nCmdShow)
{
// 640x480 window
CMyWindow appwindow;
RECT rect = {0, 0, 640, 480};
RECT rectActual = {0};
appwindow.Create(NULL, rect, L"App Window", WS_OVERLAPPEDWINDOW);
appwindow.ShowWindow(SW_SHOW);
{
MSG msg;
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
// app shutdown
appwindow.DestroyWindow();
return 0;
}
Resort to thunks or tls? I dont know what you mean by a thunk in this case, but its quite easy - if just a little convoluted - to bootstrap a window into a c++ class wrapper.
class UserWindow
{
HWND _hwnd;
public:
operator HWND(){
return _hwnd;
}
UserWindow():_hwnd(0){}
~UserWindow(){
if(_hwnd){
SetWindowLongPtr(GWL_USERDATA,0);
DestroyWindow(_hwnd);
}
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){
UserWindow* self = 0;
if(uMsg == WM_CREATE)
{
LPCREATESTRUCT crst = (LPCREATESTRUCT)lParam;
self = (Window*)crst->lpCreateParams;
SetWindowLongPtr(hwnd,GWL_USERDATA,(LONG_PTR)self);
self->_hwnd = hwnd;
}
else
self = (Window*)GetWindowLongPtr(hwnd,GWL_USERDATA);
if(self){
LRESULT lr = self->WndProc(uMsg,wParam,lParam);
if(uMsg == WM_DESTROY){
if(self = (Window*)GetWindowLongPtr(hwnd,GWL_USERDATA))
self->_hwnd = NULL;
}
return lr;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
HWND Create(int x, int y, int w, int h, LPCTSTR pszTitle,DWORD dwStyle,DWORD dwStyleEx,LPCTSTR pszMenu,HINSTANCE hInstance, HWND hwndParent){
WNDCLASSEX wcex = { sizeof (wcex),0};
if(!GetClassInfo(hInstance,ClassName(),&wcex)){
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WindowndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.lpszClassName = ClassName();
OnCreatingClass( wcex );
RegisterClassEx(&wcex);
}
return CreateWindowEx( dwStyleEx, ClassName(), pszTitle, dwStyle, x, y, w, h, hwndParent, pszMenu, hInstance, this);
}
// Functions to override
virtual LPCTSTR ClassName(){
return TEXT("USERWINDOW");
}
virtual LRESULT WindowProc(UINT uMsg, WPARAM wParam,LPARAM lParam){
return DefWindowProc(uMsg,wParam,lParam);
}
virtual void Window::OnCreatingClass(WNDCLASSEX& wcex){
wcex.hCursor = LoadCursor(NULL,IDC_ARROW);
}
};
It is all a bit convoluted, but it means that the window can be destroyed safely by deleting the class, OR by being destroyed. There are one or two sizing related messages sent during the call to CreateWindow before WM_CREATE sets GWL_USERDATA to "this" but practically they are of no consequence. The window class is automatically created the first time the window is instantiated.
One thing this style of automatic class registration on the first call to create does not support is the instantiation of this type of window as a control on a dialog - To support that case a whole slew of things would need to be changed... provide a static class registration function... a "new MyClass" in the static WM_CREATE handler... its not obvious to me how this could be done in a frameworkish type fashion.
This question already has answers here:
Use class member as WNDPROC/DLGPROC with or without global
(3 answers)
Closed 7 years ago.
I am trying to work my way around the WINAPI to implement the procedure of a modeless Dialog window as member of a custom class. I am not sure it is possible, but I hoped someone knew a way. The goal is to have a procedure with access to member variables of the custom Class
I know it is possible using normal windows.
Example:
//MyClass.h
class MyClass
{
public:
bool init( ... )
static LRESULT CALLBACK redirect(HWND hWnd, UINT msg,
LPARAM lParam, WPARAM wParam);
LRESULT myWndProc(HWND hWnd, UINT msg,
LPARAM lParam, WPARAM wParam);
private:
HWND m_MainHwnd;
}
By defining a static member function that redirects the pointer to the nonstatic actual procedure handling, the procedure can be a member function:
//MyClass.cpp
MyClass::init( ... )
{
//Create the window class for the main Window//
m_windowed = windowed;
WNDCLASSEX wc; //Create a new extended windows class
wc.cbSize = sizeof(WNDCLASSEX); //Size of our windows class
wc.style = CS_HREDRAW | CS_VREDRAW; //class styles
wc.lpfnWndProc = MyClass::redirect; //Default windows procedure function
wc.cbClsExtra = NULL; //Extra bytes after our wc structure
wc.cbWndExtra = NULL; //Extra bytes after our windows instance
wc.hInstance = hInstance; //Instance to current application
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); //Title bar Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); //Default mouse Icon
wc.hbrBackground = CreateSolidBrush(0xFFFFFF); //Window bg color
wc.lpszMenuName = NULL; //Name of the menu attached to our window
wc.lpszClassName = m_windowName; //Name of our windows class
wc.hIconSm = LoadIcon(NULL, IDI_WINLOGO); //Icon in your taskbar
if (!RegisterClassEx(&wc)) //Register our windows class
{
//if registration failed, display error
MessageBox(NULL, "Error registering Main Window class",
"Error", MB_OK | MB_ICONERROR);
return false;
}
m_MainHwnd = CreateWindowEx( //Create our Extended Window
NULL, //Extended style
m_windowName, //Name of our windows class
m_windowName, //Name in the title bar of our window
WS_OVERLAPPEDWINDOW | WS_VISIBLE, //style of our window | Make it visible on showWindow cmd
30, 30, //Top left corner of window
width, //Width of our window
height, //Height of our window
NULL, //Handle to parent window
NULL, //Handle to a Menu
hInstance, //Specifies instance of current program
this //used for an MDI client window
);
}
See the line in the setup in WNDCLASSEX: wc.lpfnWndProc = MyClass::redirect;? This is valid because the the following implementation of the redirect static function:
MyClass::redirect(HWND hwnd, UINT msg, LPARAM lParam, WPARAM wParam)
{
if (msg == WM_CREATE) SetWindowLongPtr(hwnd, GWL_USERDATA, (LONG_PTR)((CREATESTRUCT FAR *)lParam)->lpCreateParams);
MyClass * pObject = (MyClass*)((LONG_PTR)GetWindowLongPtr(hwnd, GWL_USERDATA));
if (pObject) return pObject->MyWndProc(hwnd, msg, wParam, lParam);
//return the message for windows to handle it
return DefWindowProc(hwnd,
msg,
wParam,
lParam);
};
This lets you implement the MyWndProc ( ... ) exactly like any other member method.
Now! I really want to be able to do the same thing to my Modeless Dialog box - because it's rather important that it knows the member variables of "MyClass". Also - I like that I can design it and redesign it as I like ( If I have to use normal windows - It'd be tedious to design it all in code. )
Is it possible?
Thank you in advance!
Yes it's possible to use this method with a dialog box, in more or less the same way.
Instead of using WM_CREATE to store the this pointer you use WM_INITDIALOG. Note that the user data is passed to WM_INITDIALOG in lParam itself - there are no structures to dereference like there is with WM_CREATE.
You can store the pointer in DWLP_USER which is a pointer-size window data slot available to the owner of the dialog box.
The final difference is simply return FALSE if the data pointer hasn't been assigned yet - you don't call DefWindowProc from a dialog procedure.
class MyClass
{
public:
static INT_PTR CALLBACK dlgRedirect(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT myDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
}
//...
HWND hwndDlg = DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), hwndParent,
MyClass::dlgRedirect, reinterpret_cast<LPARAM>(this));
//...
INT_PTR CALLBACK MyClass::dlgRedirect(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_INITDIALOG) SetWindowLongPtr(hWnd, DWLP_USER, lParam);
MyClass* pThis = reinterpret_class<MyClass*>(GetWindowLongPtr(hWnd, DWLP_USER));
if (pThis) return pThis->myDlgProc(hWnd, uMsg, wParam, lParam);
return FALSE;
}
INT_PTR MyClass::myDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
// real dialog procedure here
}
UPDATE: As requested I have added all of the code I am using to create the Window and its RichEdit control.
I'm trying to handle windows messages for a RichEdit control used as a child of another window.
Now I did have the RichEdit control working with the exception of my own WndProc. The issue is that, when I set wc.lpszClassName = MSFTEDIT_CLASS; so that it matches lpClassName used in CreateWindowEx(), the content of the RichEdit control no longer appears to draw (ie text, etc), however, its WndProc function can then handle messages.
The creation of the window:
First the constructor:
SubWindow::SubWindow(const wchar_t *szAppNameImport)
{
szAppName = szAppNameImport;
cfmt = CHARFORMATW();
hwnd = HWND();
windowRect = RECT();
editControlHwnd = HWND();
wc = WNDCLASSEX();
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_CLASSDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = GetModuleHandle(NULL);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = szAppName;
wc.hIconSm = LoadIcon(wc.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
}
Then the Create() function:
VOID SubWindow::Create(unsigned int window_startX, unsigned int window_startY, unsigned int windowWidthInput, unsigned int windowHeightInput, HWND parent)
{
windowRect.left = window_startX;
windowRect.top = window_startY;
windowRect.right = windowWidthInput;
windowRect.bottom = windowHeightInput;
if(!RegisterClassEx(&wc))
{
throw std::exception();
}
if((hwnd = CreateWindowEx
(
WS_EX_CLIENTEDGE,
szAppName,
TEXT("Our classy sub window!"),
WS_OVERLAPPEDWINDOW| WS_VISIBLE,
windowRect.left, windowRect.top,
windowRect.right, windowRect.bottom,
parent,
NULL,
wc.hInstance,
NULL))==NULL)
{
throw std::exception();
}
SetWindowLongPtr(hwnd, GWL_USERDATA, (LONG_PTR)this);
ShowWindow(hwnd, SW_SHOWDEFAULT);
UpdateWindow(hwnd);
}
WndProc:
LRESULT CALLBACK SubWindow::WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
SubWindow *childWindowPointer = (SubWindow*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
if(childWindowPointer != NULL)
{
if(childWindowPointer->GetEditControl() == hwnd)
OutputDebugString(L"I SHOULD NOT BE CALLED");
return childWindowPointer->MsgProc(hwnd, uMsg, wParam, lParam);
}
else
{
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
MsgProc:
LRESULT SubWindow::MsgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
switch(uMsg)
{
case WM_WINDOWPOSCHANGED:
{
GetClientRect(hwnd, &windowRect);
SetWindowPos(editControlHwnd, NULL, windowRect.left, windowRect.top, windowRect.right, windowRect.bottom, SWP_NOZORDER | SWP_NOACTIVATE);
return 0;
}
case WM_DESTROY:
{
OutputDebugString(TEXT("DESTROYING A SUB WINDOW!\n"));
return 0;
}
case WM_PAINT:
{
InvalidateRect (hwnd, NULL, FALSE);
hdc = BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
return 0;
}
case EM_EXSETSEL:
{
if(hwnd == editControlHwnd)
{
OutputDebugString(L"Text selection changed");
return 0;
}
}
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
The RichEdit control draws and functions perfectly, apparently without issue, with the exception of it not using the WndProc I have defined.
I'm not sure what I'm doing wrong here or how I can correctly resolve this.
EDIT:
Based on the answers and comments, I have restored my code to use only a Window class which contains a RichEdit control, created thusly:
void SubWindow::CreateEditControl()
{
std::wstring initialText = TEXT("TestWindow\r\n");
LoadLibrary(L"Msftedit.dll");
GetClientRect(hwnd, &windowRect);
editControlHwnd = CreateWindowEx(0, MSFTEDIT_CLASS, initialText.data(),
WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_READONLY | WS_VSCROLL | ES_NOHIDESEL,
windowRect.left, windowRect.top,windowRect.right,windowRect.bottom,
hwnd,
NULL, NULL, NULL);
cfmt.cbSize = sizeof(CHARFORMAT);
cfmt.dwMask = CFM_COLOR | CFM_FACE | CFM_SIZE;
cfmt.dwEffects = 0;
cfmt.yHeight = 160;
cfmt.crTextColor = RGB(0,0,0);
wcscpy_s(cfmt.szFaceName, TEXT("Tahoma"));
SendMessage(editControlHwnd, EM_SETCHARFORMAT, SCF_DEFAULT, (LPARAM)&cfmt);
}
How do I process the messages from this control in the Window's MsgProc?
When you create a rich edit control window using the default class name (MSFTEDIT_CLASS), all messages are going to be sent to its parent window. Since you are not that parent window, you are not able to handle those messages.
So you will need to subclass the control, substituting your own window procedure that will be called directly, instead of allowing the messages to be passed on to the parent. That is simple to do; I've discussed it before in this answer for a regular edit control. The altered example code looks like this:
// Stores the old original window procedure for the rich edit control.
WNDPROC wpOldRichEditProc;
// The new custom window procedure for the rich edit control.
LRESULT CALLBACK CustomRichEditProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
...
}
// Pass the messages you don't process on to the original window procedure.
CallWindowProc(wpOldRichEditProc, hWnd, msg, wParam, lParam);
}
And when you create the control:
// Create the rich edit control
HWND hWnd = CreateWindowEx(...)
// Subclass it.
wpOldRichEditProc= (WNDPROC)SetWindowLongPtr(hWnd,
GWLP_WNDPROC,
(WNDPROC)CustomRichEditProc);
You will also need to make sure to unsubclass the control whenever it is destroyed. The other example demonstrates doing that in response to messages received by the parent window, but that won't work in your case, since you're not getting messages for the parent window. Instead, you'll need to remove the subclass from the control in response to its own WM_NCDESTROY message:
SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)wpOldRichEditProc);
Or, version 6 of the common controls library introduced a new, less error-prone method of subclassing using a set of utility functions. (The critical functionality was actually there in earlier versions, but it was undocumented.) Considering that you do not have control over the process that actually owns the window, this is arguably the preferred approach.
There is a demo of both approaches here on MSDN.
And of course, you don't have to subclass only individual controls. You can also register a custom window class that behaves the same way as the built-in rich edit control, but still gives you first crack at the messages received by windows of that class. I can't tell from the question whether that's necessary or not; it sounds like you only have a single control you care about.
You say that the original problem was that your parent window was not getting the notification messages from the RichEdit control. Did you send a EM_SETEVENTMASK message to the RichEdit control? If you don't, the RichEdit control will not send certain notification messages to its parent window. See EM_SETEVENTMASK message.
Can you show your code involving the wc structure and the creation of the window? I'm fairly sure you don't want the main window to have the same class as the rich edit control - and that's what I'm reading so far.
I don't even know why you have a WNDCLASSEX apply to a rich edit control.
My suggestion is that you simplify things and "subclass" the rich edit control after it has been created, using SetWindowLong() with GWL_WNDPROC to your EditControl::WndProc.
Ok this is a really weird problem. I wanna start off by saying that I'm not a beginner in c++ and I'm certainly not advanced. I'm somewhere in the middle. What I'm trying to do is make a C++ OOP wrapper library (dll) of the Win32 API. Here are the classes of my library. I compiled it with Mingw using the command:
g++ -shared -o bin\win32oop.dll src\Application.cpp src\Form\Form.cpp -Wall
src\Application.h:
#ifndef WOOP_APPLICATION_H_
#define WOOP_APPLICATION_H_
namespace Woop
{
class Application
{
public:
bool Init(void);
virtual bool OnInit(void);
};
}
#endif // WOOP_APPLICATION_H_
src\Application.cpp
#include <windows.h>
#include "Application.h"
#include "Form\Form.h"
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
namespace Woop
{
bool Application::Init(void)
{
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = GetModuleHandle(NULL);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = "woop";
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(RegisterClassEx(&wc) == 0)
{
MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
return false;
}
this->OnInit();
return true;
}
bool Application::OnInit(void)
{
return true;
}
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
Woop::Form *wnd = 0;
if (uMsg == WM_NCCREATE)
{
SetWindowLong (hwnd, GWL_USERDATA, long((LPCREATESTRUCT(lParam))->lpCreateParams));
}
wnd = (Woop::Form *)(GetWindowLong (hwnd, GWL_USERDATA));
if (wnd) return wnd->WndProc(hwnd, uMsg, wParam, lParam);
return ::DefWindowProc (hwnd, uMsg, wParam, lParam);
}
src\Form\Form.h
#ifndef WOOP_FORM_FORM_H_
#define WOOP_FORM_FORM_H_
namespace Woop
{
class Form
{
public:
bool Show(void);
virtual LRESULT WndProc(HWND, UINT, WPARAM, LPARAM);
protected:
HWND _handle;
};
}
#endif // WOOP_FORM_FORM_H_
src\Form\Form.cpp
#include <windows.h>
#include "Form.h"
namespace Woop
{
bool Form::Show(void)
{
_handle = CreateWindowEx(WS_EX_CLIENTEDGE, "woop", "", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, GetModuleHandle(NULL), this);
if(_handle == NULL)
{
MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
return false;
}
ShowWindow(_handle, SW_SHOWNORMAL);
return true;
}
LRESULT Form::WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
Here is a the program that I'm testing the library with:
class SampleApp : public Woop::Application
{
bool OnInit(void)
{
Form form;
form.Show();
return true;
}
};
INT APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, INT)
{
SampleApp application;
if(application.Init() == false) return 0;
MSG Msg;
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return 0;
}
Alright, now the problem. Do you see that virtual Window Procedure in the Form class? If I remove the virtual from the declaration, the program compiles and runs fine. But when I add it back, it crashes. The infamous "Don't Send" dialog comes up. I'm not sure when it crashes, i'll try to figure that out using MessageBox() (lol, it's what I get for not learning how to debug with gdb). I'm trying to make it so that I can make a class such as LoginForm and derive from Form and override the Window Procedure. I hope I explained the problem well enough :D. This might be a compiler bug or my stupidity :P. Anyways, thanks in advance.
The problem is here:
bool OnInit(void)
{
Form form;
form.Show();
return true;
}
The form object is destroyed when this method is returned.
So the this pointer that you stored when you call Show() is no longer valid.
_handle = CreateWindowEx(WS_EX_CLIENTEDGE, "woop", "", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL,
GetModuleHandle(NULL),
/* Here ----> */ this
);
When you try and do the dispatch it is getting reallyed screwed up because it is using the this pointer to work out the address of the virtual function to call.
The reason that it crasshes with virtual and not when you take virtual away is that virtual method address is calculated at runtime while the normal method address is planted at compile time.
When calculating the address of the virtual method the this pointer is dereferenced in some way (which in this case leads to UB) but because the object is been destroyed the data at that address has proably been re-used so the address you get for the function is some random junk and calling this will never be good.
A simple solution is to make the form part of the application object.
Thus its lifetime is the same as the application:
class SampleApp : public Woop::Application
{
Form form;
bool OnInit(void)
{
form.Show();
return true;
}
};
wc.lpfnWndProc = WndProc;
That cannot work in the general case, although it is not obvious where that WndProc is located. Windows is not going to supply the "this" pointer that an instance method needs when it makes the callback. You are getting away with it right now because you don't access any members of the Form class in your Form::WndProc() method. It works by accident without the virtual keyword but that luck will quickly run out once you start touching members. That will bomb with an AccessViolation exception.
You need to make the Form::WndProc() method a static method.
Making it virtual is going to require you writing code that maps the HWND to a Form instance. This is a pretty standard feature of any class library that wraps the Win32 API. There's lots of value in not having to re-invent that wheel.
I don't know if it is the problem here, but a virtual function is always called indirectly. This means the object is accessed to read the virtual function table, before the virtual function is called. That means that if the object has been overwritten (already deleted, buffer overflow on heap or stack etc..), virtual methods are more likely to crash than others.
This is especially true because most of the member variables are not causing a crash when they are corrupted, so sometimes you can oversee a heap / stack corruption problem easily.
BTW: Starting debugging with gdb is quite simple sometimes: Just load it in gdb (gdb myprogram) and enter run. When the programm crashes get the backtrace with "bt" and you should see if the crash occured inside the virtual method or when calling it.
I have been working with C++ and Win32 (non MFC/ATL) I am playing around with writing my own class library to wrap certain Win32 objects (HWNDs in particular).
When it comes to creating windows, I find the "RegisterClassEx / CreateWindowEx" method very awkward. This design makes it hard to write simple class wrappers (one must resort to thunks, or TLS or some other complicated mechanism).
It seems to me it would have been simpler to just let the application specify the window procedure and a user-data pointer at window creation time.
Is there any obvious reason I'm missing for the design choice here? Is there a really simple and efficient way for this to work?
ATL's CWindow and CWindowImpl are your friends.
CWindowImpl makes takes care of the RegisterClass/CreateWindow awkwardness that you speak of.
CWindow is a basic "wrapper" class for an HWND with all the win32 functions abstracted out.
The reason I prefer ATL over MFC. ATL is a very lightweight set of classes with all the source code provided. It's a simple #include with no extra libraries or runtimes to deal with. After rolling my own WndProcs and window encapsulation classes for many years, I've found CWindowImpl a joy to work with. You have to declare a global AtlModuleExe instance in your code to use it, but besides that, ATL stays out of the way.
Links to documenation for these classes below:
CWindow:
http://msdn.microsoft.com/en-us/library/d19y607d.aspx
CWindowImpl:
http://msdn.microsoft.com/en-us/library/h4616bh2.aspx
Update: Here's some sample code I dug up for you:
class CMyApp : public CAtlExeModuleT<CMyApp>
{
public:
static HRESULT InitializeCom()
{
CoInitialize(NULL);
return S_OK;
}
};
CMyApp g_app;
class CMyWindow : public CWindowImpl<CMyWindow>
{
public:
CMyWindow();
~CMyWindow();
BEGIN_MSG_MAP(CMyWindow)
MESSAGE_HANDLER(WM_PAINT, OnPaint);
MESSAGE_HANDLER(WM_CLOSE, OnClose);
END_MSG_MAP();
LRESULT OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
};
LRESULT CMyWindow::OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled)
{
// your WM_PAINT code goes here
}
LRESULT CMyWindow::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled)
{
PostQuitMessage();
}
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdline, int nCmdShow)
{
// 640x480 window
CMyWindow appwindow;
RECT rect = {0, 0, 640, 480};
RECT rectActual = {0};
appwindow.Create(NULL, rect, L"App Window", WS_OVERLAPPEDWINDOW);
appwindow.ShowWindow(SW_SHOW);
{
MSG msg;
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
// app shutdown
appwindow.DestroyWindow();
return 0;
}
Resort to thunks or tls? I dont know what you mean by a thunk in this case, but its quite easy - if just a little convoluted - to bootstrap a window into a c++ class wrapper.
class UserWindow
{
HWND _hwnd;
public:
operator HWND(){
return _hwnd;
}
UserWindow():_hwnd(0){}
~UserWindow(){
if(_hwnd){
SetWindowLongPtr(GWL_USERDATA,0);
DestroyWindow(_hwnd);
}
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){
UserWindow* self = 0;
if(uMsg == WM_CREATE)
{
LPCREATESTRUCT crst = (LPCREATESTRUCT)lParam;
self = (Window*)crst->lpCreateParams;
SetWindowLongPtr(hwnd,GWL_USERDATA,(LONG_PTR)self);
self->_hwnd = hwnd;
}
else
self = (Window*)GetWindowLongPtr(hwnd,GWL_USERDATA);
if(self){
LRESULT lr = self->WndProc(uMsg,wParam,lParam);
if(uMsg == WM_DESTROY){
if(self = (Window*)GetWindowLongPtr(hwnd,GWL_USERDATA))
self->_hwnd = NULL;
}
return lr;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
HWND Create(int x, int y, int w, int h, LPCTSTR pszTitle,DWORD dwStyle,DWORD dwStyleEx,LPCTSTR pszMenu,HINSTANCE hInstance, HWND hwndParent){
WNDCLASSEX wcex = { sizeof (wcex),0};
if(!GetClassInfo(hInstance,ClassName(),&wcex)){
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WindowndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.lpszClassName = ClassName();
OnCreatingClass( wcex );
RegisterClassEx(&wcex);
}
return CreateWindowEx( dwStyleEx, ClassName(), pszTitle, dwStyle, x, y, w, h, hwndParent, pszMenu, hInstance, this);
}
// Functions to override
virtual LPCTSTR ClassName(){
return TEXT("USERWINDOW");
}
virtual LRESULT WindowProc(UINT uMsg, WPARAM wParam,LPARAM lParam){
return DefWindowProc(uMsg,wParam,lParam);
}
virtual void Window::OnCreatingClass(WNDCLASSEX& wcex){
wcex.hCursor = LoadCursor(NULL,IDC_ARROW);
}
};
It is all a bit convoluted, but it means that the window can be destroyed safely by deleting the class, OR by being destroyed. There are one or two sizing related messages sent during the call to CreateWindow before WM_CREATE sets GWL_USERDATA to "this" but practically they are of no consequence. The window class is automatically created the first time the window is instantiated.
One thing this style of automatic class registration on the first call to create does not support is the instantiation of this type of window as a control on a dialog - To support that case a whole slew of things would need to be changed... provide a static class registration function... a "new MyClass" in the static WM_CREATE handler... its not obvious to me how this could be done in a frameworkish type fashion.