how to create a hidden window by extending CWnd class in visual c++

2.4k views Asked by At

Can any one help me in creating a Hidden window by extending CWnd class. I'm new to windows programming. I've tried creating one, but the issue is code breaks down when trying to register the window class or creating a window.

class HiddenWindow : public CWnd
{
public:
   HiddenWindow();
   ~HiddenWindow();
protected:
   afx_msg LRESULT DoNOOP(WPARAM wParam, LPARAM lParam);
   DECLARE_MESSAGE_MAP()

};
This is my .cpp file

HiddenWindow::HiddenWindow()
{
   CString wcn = ::AfxRegisterWndClass(NULL);//code fails here because of AfxGetInstanceHandle( )
   BOOL created = this->CreateEx(0, wcn, _T("YourHiddenWindowClass"), 0, 0, 0, 0, NULL,HWND_MESSAGE,0);
}


HiddenWindow::~HiddenWindow()
{
}

BEGIN_MESSAGE_MAP(HiddenWindow, CWnd)
ON_MESSAGE(WM_USER + 1, DoNOOP)
END_MESSAGE_MAP()

LRESULT HiddenWindow::DoNOOP(WPARAM wParam, LPARAM lParam)
{
   AfxMessageBox(_T("Test"));
   return LRESULT(true);
}
2

There are 2 answers

3
Kjell Gunnar On BEST ANSWER

I have done this in MFC by overriding the Create, the constructor is way too early Try :

BOOL HiddenWindow::Create()
{  
    if (!CWnd::CreateEx(0, AfxRegisterWndClass(0),
        _T("HiddenWindow Notification Sink"),
        WS_OVERLAPPED, 0, 0, 0, 0, NULL, NULL))
    {
        TRACE0("Warning: unable to create HiddenWindow window!\n");
        return FALSE;
    }
    return TRUE;
}
0
JohnCz On

you are not

"extending CWnd class"

you are using C++ not C#, hence you are deriving class.

You do not really have to do it if you need basic functionality. Just call create passing windows styles you need without WS_VISIBLE, as you did. You have to however provide window class as an argument since your window is not a child window.

If you need to handle messages or need to implement different that default behavior you have to derive own class but still you do not have to override Create member.

You should never do anything but initialize member variables in the constructor. You should never try to allocate memory or call other functions the may allocate memory. you should not do anything that may cause irrevocable error. There is no way to gracefully exit if contractor fails.