Null handle error - c++

I am working on a Win32++ application that has a listview in the main window. This is my code:
HWND CarsListView = NULL;
switch (message)
{
case WM_SHOWWINDOW:
CarsListView = CreateListView(hWnd);
ShowWindow(CarsListView, SW_SHOW);
break;
case WM_SIZING:
{
if(!CarsListView)
MessageBox(hWnd, _T("Null handle."), _T("Error"), MB_ICONERROR | MB_OK);
RECT WindowRect;
GetWindowRect( hWnd, &WindowRect);
SetWindowPos(CarsListView, NULL, 0, 0, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, SWP_SHOWWINDOW);
}
break;
// ...
}
and the CreateListView definition is this:
HWND CreateListView (HWND hwndParent)
{
INITCOMMONCONTROLSEX icex; // Structure for control initialization.
icex.dwICC = ICC_LISTVIEW_CLASSES;
InitCommonControlsEx(&icex);
RECT rcClient; // The parent window's client area.
GetClientRect (hwndParent, &rcClient);
// Create the list-view window in report view with label editing enabled.
HWND hWndListView = CreateWindow(WC_LISTVIEW,
L"",
WS_CHILD | LVS_REPORT | LVS_EDITLABELS,
0, 0,
rcClient.right - rcClient.left,
rcClient.bottom - rcClient.top,
hwndParent,
/*(HMENU)*/NULL,
hInst,
NULL);
return (hWndListView);
}
When the window receives WM_SIZING, I get that CarsListView = NULL
What can I do to have that handle pointing to my listview?

Three way to do that kind of stuff.
The Ugly
Store your CarsListView HWND in a static. You can't have 2 instance of the parent windows.
The Bad
Use SetWindowsLongPtr(parentHWND,GWLP_USERDATA,CarsListViewHWND) in your init and GetWindowLongPtr when needed. It's fast you can have as many instance as you want, but if you need more than one information I recommend storing a struct with your HWND inside instead of single HWND for future extensibility.
The Good ?
Use SetProp(parentHWND,"Your Unique String",hDataHandle); its by far the more code but with that usage you can use it on every windows without caring if the USERDATA is already used or not. It's the best approach when you need to add personal property to a windows/code you can't be sure how it will be used or change over time

There are two ways to do this: The "good" way and the "bad" way.
The "bad" way is to simply declare the local variable as static, however it means you can't create two windows of this type in the same process.
The "good" way is to memorize it in a heap-allocated structure, and store a pointer to this structure in the Window information using SetWindowLongPtr(). You can then retrieve this structure with GetWindowLongPtr().

I would create the listview in WM_CREATE and not in WM_SHOWWINDOW. Also make the handle either global or static.
Or you can also create the list view globally and keep it hidden and just make it visible and set its position whenever you want it to do.

Related

Who should be the parent of a tab control child dialog?

According to some sources, a tab child dialog should be the child of the actual main dialog window, not the tab control itself. I think some of the docs suggest the opposite, namely this function example:
// Creates a child window (a static control) to occupy the tab control's
// display area.
// Returns the handle to the static control.
// hwndTab - handle of the tab control.
//
HWND DoCreateDisplayWindow(HWND hwndTab)
{
HWND hwndStatic = CreateWindow(WC_STATIC, L"",
WS_CHILD | WS_VISIBLE | WS_BORDER,
100, 100, 100, 100, // Position and dimensions; example only.
hwndTab, NULL, g_hInst, // g_hInst is the global instance handle
NULL);
return hwndStatic;
}
So is there a definitive view on this? I checked Petzold, by the way, but didn't locate anything on the subject. Thanks for any help.

c++ win32 edit box cursor not flashing

I'm a newbie in windows programming and am continuously running into different kinds of problems, most of which I have been able to solve by myself.
My problem at hand is the caret (or cursor) shown in text areas. The thing that indicates where you are typing your text? Well it is shown, at least, but it doesn't blink like it should.
I have an EDIT box created in WM_CREATE like so:
case WM_CREATE:
{
if(!logged) {
HWND userField = CreateWindow(
"EDIT", // Predefined class; Unicode assumed
NULL, // Button text
WS_VISIBLE | WS_CHILD | WS_BORDER | ES_LEFT, // Styles
C_WIDTH/2 - 80, // x position
C_HEIGHT - 240, // y position
160, // Button width
25, // Button height
hwnd, // Parent window
NULL, // No menu.
(HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE),
NULL); // Pointer not needed.
// initialize NONCLIENTMETRICS structure
NONCLIENTMETRICS ncm;
ncm.cbSize = sizeof(ncm);
// obtain non-client metrics
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0);
// create the new font
HFONT hNewFont = CreateFontIndirect(&ncm.lfMessageFont);
// set the new font
SendMessage(userField, WM_SETFONT, (WPARAM)hNewFont, 0);
}
}
break;
That is all code concerning the edit box. I'm sorry if I'm not being clear enough or my supply of code is lacking; I'm unsure of what parts of code is relevant here and what are irrelevant. I don't think I should paste my whole code here, either.
The problem, again, is that the caret in the textbox (userField) does not blink.
Please ask for more details if you need them.
Using your code, I didn't get a flashing caret. But then i added:
SetFocus( userField );
and voilĂ , a flashing caret :-)
This may not be the problem the OP was experiencing, but I was experiencing the same symptom, and I'm posting my solution here in case someone else experiences this problem...
In short, if you subclass an edit control, and handle the WM_SETFOCUS event, you need to call DefSubclassProc() or your caret won't show up. Presumably, you can call ShowCaret() yourself, but you're probably safer just calling DefSubclassProc() in case there's other processing that needs to happen.
After playing around - making my code a bit tidier and stuff - I accidentally solved this on my own
I changed
HWND userField = CreateWindow(
"EDIT", // Predefined class; Unicode assumed
NULL, // Button text
WS_VISIBLE | WS_CHILD | WS_BORDER | ES_LEFT, // Styles
C_WIDTH/2 - 80, // x position
C_HEIGHT - 240, // y position
160, // Button width
25, // Button height
hwnd, // Parent window
NULL, // No menu.
(HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE),
NULL); // Pointer not needed.
Into
HWND userField = CreateWindow("EDIT", NULL, WS_VISIBLE | WS_CHILD | WS_BORDER | ES_LEFT,
C_WIDTH/2 - 80, C_HEIGHT - 240, 160, 25, hwnd, NULL, g_hInstance, NULL);
The only difference there is the hInstance: in the first code it was apparently wrong. I changed it into my global reference of hInstance.

create a CAxWindow inside a BHO (C++)

I'm having trouble opening a new CAxWindow inside my BHO, I can see the request to "microsoft.com" being fired but no window is shown.
I tried many different ways, this is my last, anyone has a clue what's wrong?
thanks.
CAxWindow m_axWindow;
CRect rc;
HWND wndIE = NULL;
m_pWebBrowser->get_HWND((SHANDLE_PTR*)&wndIE);
GetWindowRect(wndIE, &rc);
CSize sz = CSize(100, 200);
CRect rcPage = new CRect(10, 10, 10, 10);
m_axWindow.Create(wndIE, rcPage, _TEXT("http://www.microsoft.com"), WS_POPUP | WS_TABSTOP, 0, 0U, 0);
HRESULT hRet = m_axWindow.QueryControl(IID_IWebBrowser2, (void**)&m_pWebBrowser);
I think m_axWindow.Create creates a child window. Check its style for WS_CHILD after that call. You probably need to create a plain popup top-level window first, then create a CAxWindow using that popup window as parent, not the wndIE. Make sure to do ShowWindow on the pop-up, too.

Can't use PropSheet to create a centered property sheet dialog

I am creating a modeless property sheet using the following settings:
PROPSHEETHEADER pshdr = { 0 };
pshdr.dwSize = sizeof(PROPSHEETHEADER);
pshdr.dwFlags = PSH_NOAPPLYNOW | PSH_PROPSHEETPAGE |
PSH_MODELESS | PSH_USECALLBACK;
pshdr.pfnCallback = PropSheetProc;
pshdr.hwndParent = mGlobalState->trayWin;
pshdr.pszCaption = L"My Settings";
pshdr.nPages = mPages.size();
pshdr.ppsp = mWinPages;
In PropSheetProc, I catch the PSCB_PRECREATE message and modify the dialog template so that it gets the DS_CENTER style:
static int CALLBACK
PropSheetProc(HWND hwndDlg, // IN
UINT uMsg, // IN
LPARAM lParam) // IN
{
// Before the dialog is created, bless it with the DS_CENTER style.
if (uMsg == PSCB_PRECREATE) {
DLGTEMPLATE *dlgTemplate = (DLGTEMPLATE *)lParam;
_ASSERT(dlgTemplate);
dlgTemplate->style |= DS_CENTER;
}
return 0;
}
However this doesn't succeed in centering the dialog. I tried to catch PSCB_INITIALIZED instead and call a CenterWindow method on the hwnd passed to the PropSheetProc:
void
CenterWindow(HWND hwndWindow) // IN
{
int nX, nY, nScreenWidth, nScreenHeight;
RECT rectWindow;
nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
GetWindowRect(hwndWindow, &rectWindow);
nX = (nScreenWidth - (rectWindow.right - rectWindow.left)) / 2;
nY = (nScreenHeight - (rectWindow.bottom - rectWindow.top)) / 2;
SetWindowPos(hwndWindow, 0, nX, nY, 0, 0,
SWP_NOZORDER | SWP_NOSIZE);
}
But that doesn't work either!
Finally, I moved the CenterWindow call to directly after the PropSheet call:
mHwnd = (HWND)PropertySheet(&pshdr);
CenterWindow(mHwnd);
return mHwnd != NULL;
And this DOES work, though on a heavily loaded system, the dialog flashes from its initial position over to its final position, which is suboptimal.
Using the PropSheetProc to modify the DLGTEMPLATE structure seems intuitive. Actually, I can apply other window styles. But DS_CENTER seems to have no effect. So what am I doing wrong? There's many ways I can work around this brokennness but why is it broken in the first place?
Overload the InitialUpdate() of the CPropertySheet, and place the CenterWindow() call there. This happens before the window is drawn on the screen, but after it is created, so it's hwnd will be valid. There is nothing broken. The dialog has to be Created to have a valid HWND. Alternatively, if your working with the resource editor you can set it's property to centered, and it will achieve the same result. Why are you overloading the WinProc for the propertysheet? The whole reason MFC uses message maps was to eliminate the need to even touch WinProc's.
If your using raw win api in a SDK style application ::
Handle WM_CREATE in the WinProc of the property sheet. The LPCREATE struct in the LPARAM will contain a valid HWND from the create call. Just make sure you pass the proper parameters back to WndProcDefault() otherwise window creation will fail.

Windows API dialogs without using resource files

I'm trying to create a dialog box using C++ and the windows API, but I don't want the dialog defined in a resource file. I can't find anything good on this on the web, and none of the examples I've read seem to define the dialog programmatically.
How can I do this?
A simple example is fine. I'm not doing anything complicated with it yet.
Raymond Chen wrote a few posts about the dialog manager:
The dialog manager, part 1: Warm-ups
The dialog manager, part 2: Creating the frame window
The dialog manager, part 3: Creating the controls
The dialog manager, part 4: The dialog loop
The dialog manager, part 5: Converting a non-modal dialog box to modal
The dialog manager, part 6: Subtleties in message loops
The dialog manager, part 7: More subtleties in message loops
The dialog manager, part 8: Custom navigation in dialog boxes
The dialog manager, part 9: Custom accelerators in dialog boxes
If all you want to do is show a window with controls, it's possible to create a window without using resource (.rc) files / scripts.
This isn't the same as a dialog, but it might be easier than creating a dialog programmatically.
First, a few notes about how this is done:
Instead of designing the dialog in the rc file, you could manually use CreateWindow (or CreateWindowEx) to create child windows of a main window. (for .NET Windows Forms programmers, these windows are like Controls).
This process will not be graphical at all (you will need to manually type in the location and size of each window), but I think this can be a great way to understand how dialogs are created under the hood.
There are some disadvantages to not using a real dialog, namely that tab will not work when switching between controls.
About the example:
This example features a dialog box with two buttons, an edit box (.NET Windows Forms programmers would think of it as a TextBox), and a check box.
It has been tested under the following conditions:
x86 build
x64 build
Unicode build (UNICODE and _UNICODE defined)
Non-Unicode build (UNICODE and _UNICODE not defined)
Built with Visual Studio's C compiler
Built with Visual Studio's C++ compiler
OS: Windows 10 64 bit
Note: UNICODE
As of the time of writing, UTF-8 is still in beta for Windows 10
If you have not enabled this setting, you should assume that any char* is ACP, not UTF-8, this applies to standard library functions too
Even though in Linux, that same standard library function would be UTF-8.
Sadly, some C++ standard library features only work with char* (e.g., exception messages).
You can still use UTF-8 in Windows without the option set, you will just have to encode it back to UTF-16 before calling winapi functions.
Here is a reddit thread with a reply from somebody who claims to have worked on UTF-8 on Windows, it has some good information.
UNICODE in Windows means "UTF-16", not "UTF-8".
Using Unicode of some kind is strongly recommended for any version of Windows that is not very old.
Be aware that if you don't use Unicode, your program may be utterly unable to open file names containing Unicode characters, handle directories (e.g., usernames) with non-ACP characters, etc.
Using ACP functions (SendMessageA,etc) without somehow verifying that UTF-8 is enabled (it's disabled by default) is probably a bug.
For max portability/flexibility, I would recommend using UTF-16 and the W version of all API functions, translating from UTF-8 to UTF-16 at the last minute. Read this page very carefully.
Now for the code:
Note that a large amount of comments have been added to try to document the windows functions, I recommend copy/pasting this into a text editor, for best results.
// This sample will work either with or without UNICODE, it looks like
// it's recommended now to use UNICODE for all new code, but I left
// the ANSI option in there just to get the absolute maximum amount
// of compatibility.
//
// Note that UNICODE and _UNICODE go together, unfortunately part
// of the Windows API uses _UNICODE, and part of it uses UNICODE.
//
// tchar.h, for example, makes heavy use of _UNICODE, and windows.h
// makes heavy use of UNICODE.
#define UNICODE
#define _UNICODE
//#undef UNICODE
//#undef _UNICODE
#include <windows.h>
#include <tchar.h>
// I made this struct to more conveniently store the
// positions / size of each window in the dialog
typedef struct SizeAndPos_s
{
int x, y, width, height;
} SizeAndPos_t;
// Typically these would be #defines, but there
// is no reason to not make them constants
const WORD ID_btnHELLO = 1;
const WORD ID_btnQUIT = 2;
const WORD ID_CheckBox = 3;
const WORD ID_txtEdit = 4;
const WORD ID_btnShow = 5;
// x, y, width, height
const SizeAndPos_t mainWindow = { 150, 150, 300, 300 };
const SizeAndPos_t btnHello = { 20, 50, 80, 25 };
const SizeAndPos_t btnQuit = { 120, 50, 80, 25 };
const SizeAndPos_t chkCheck = { 20, 90, 185, 35 };
const SizeAndPos_t txtEdit = { 20, 150, 150, 20 };
const SizeAndPos_t btnShow = { 180, 150, 80, 25 };
HWND txtEditHandle = NULL;
// hwnd: All window processes are passed the handle of the window
// that they belong to in hwnd.
// msg: Current message (e.g., WM_*) from the OS.
// wParam: First message parameter, note that these are more or less
// integers, but they are really just "data chunks" that
// you are expected to memcpy as raw data to float, etc.
// lParam: Second message parameter, same deal as above.
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
// Create the buttons
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Note that the "parent window" is the dialog itself. Since we are
// in the dialog's WndProc, the dialog's handle is passed into hwnd.
//
//CreateWindow( lpClassName, lpWindowName, dwStyle, x, y, nWidth, nHeight, hWndParent, hMenu, hInstance, lpParam
//CreateWindow( windowClassName, initial text, style (flags), xPos, yPos, width, height, parentHandle, menuHandle, instanceHandle, param);
CreateWindow( TEXT("Button"), TEXT("Hello"), WS_VISIBLE | WS_CHILD, btnHello.x, btnHello.y, btnHello.width, btnHello.height, hwnd, (HMENU)ID_btnHELLO, NULL, NULL);
CreateWindow( TEXT("Button"), TEXT("Quit"), WS_VISIBLE | WS_CHILD, btnQuit.x, btnQuit.y, btnQuit.width, btnQuit.height, hwnd, (HMENU)ID_btnQUIT, NULL, NULL);
// Create a checkbox
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CreateWindow( TEXT("button"), TEXT("CheckBox"), WS_VISIBLE | WS_CHILD | BS_CHECKBOX, chkCheck.x, chkCheck.y, chkCheck.width, chkCheck.height, hwnd, (HMENU)ID_CheckBox, NULL, NULL);
// Create an edit box (single line text editing), and a button to show the text
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Handle = CreateWindow(windowClassName, windowName, style, xPos, yPos, width, height, parentHandle, menuHandle, instanceHandle, param);
txtEditHandle = CreateWindow(TEXT("Edit"), TEXT("Initial Text"), WS_CHILD | WS_VISIBLE | WS_BORDER, txtEdit.x, txtEdit.y, txtEdit.width, txtEdit.height, hwnd, (HMENU)ID_txtEdit, NULL, NULL);
//CreateWindow( windowClassName, windowName, style, xPos, yPos, width, height, parentHandle, menuHandle, instanceHandle, param);
CreateWindow( TEXT("Button"), TEXT("Show"), WS_VISIBLE | WS_CHILD, btnShow.x, btnShow.y, btnShow.width, btnShow.height, hwnd, (HMENU)ID_btnShow, NULL, NULL);
// Create an Updown control. Note that this control will allow you to type in non-number characters, but it will not affect the state of the control
break;
// For more information about WM_COMMAND, see
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms647591(v=vs.85).aspx
case WM_COMMAND:
// The LOWORD of wParam identifies which control sent
// the WM_COMMAND message. The WM_COMMAND message is
// sent when the button has been clicked.
if (LOWORD(wParam) == ID_btnHELLO)
{
MessageBox(hwnd, TEXT("Hello!"), TEXT("Hello"), MB_OK);
}
else if (LOWORD(wParam) == ID_btnQUIT)
{
PostQuitMessage(0);
}
else if (LOWORD(wParam) == ID_CheckBox)
{
UINT checked = IsDlgButtonChecked(hwnd, ID_CheckBox);
if (checked)
{
CheckDlgButton(hwnd, ID_CheckBox, BST_UNCHECKED);
MessageBox(hwnd, TEXT("The checkbox has been unchecked."), TEXT("CheckBox Event"), MB_OK);
}
else
{
CheckDlgButton(hwnd, ID_CheckBox, BST_CHECKED);
MessageBox(hwnd, TEXT("The checkbox has been checked."), TEXT("CheckBox Event"), MB_OK);
}
}
else if (LOWORD(wParam) == ID_btnShow)
{
int textLength_WithNUL = GetWindowTextLength(txtEditHandle) + 1;
// WARNING: If you are compiling this for C, please remember to remove the (TCHAR*) cast.
TCHAR* textBoxText = (TCHAR*) malloc(sizeof(TCHAR) * textLength_WithNUL);
GetWindowText(txtEditHandle, textBoxText, textLength_WithNUL);
MessageBox(hwnd, textBoxText, TEXT("Here's what you typed"), MB_OK);
free(textBoxText);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
// hInstance: This handle refers to the running executable
// hPrevInstance: Not used. See https://blogs.msdn.microsoft.com/oldnewthing/20040615-00/?p=38873
// lpCmdLine: Command line arguments.
// nCmdShow: a flag that says whether the main application window
// will be minimized, maximized, or shown normally.
//
// Note that it's necessary to use _tWinMain to make it
// so that command line arguments will work, both
// with and without UNICODE / _UNICODE defined.
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
MSG msg;
WNDCLASS mainWindowClass = { 0 };
// You can set the main window name to anything, but
// typically you should prefix custom window classes
// with something that makes it unique.
mainWindowClass.lpszClassName = TEXT("JRH.MainWindow");
mainWindowClass.hInstance = hInstance;
mainWindowClass.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
mainWindowClass.lpfnWndProc = WndProc;
mainWindowClass.hCursor = LoadCursor(0, IDC_ARROW);
RegisterClass(&mainWindowClass);
// Notes:
// - The classname identifies the TYPE of the window. Not a C type.
// This is a (TCHAR*) ID that Windows uses internally.
// - The window name is really just the window text, this is
// commonly used for captions, including the title
// bar of the window itself.
// - parentHandle is considered the "owner" of this
// window. MessageBoxes can use HWND_MESSAGE to
// free them of any window.
// - menuHandle: hMenu specifies the child-window identifier,
// an integer value used by a dialog box
// control to notify its parent about events.
// The application determines the child-window
// identifier; it must be unique for all
// child windows with the same parent window.
//CreateWindow( windowClassName, windowName, style, xPos, yPos, width, height, parentHandle, menuHandle, instanceHandle, param);
CreateWindow( mainWindowClass.lpszClassName, TEXT("Main Window"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, mainWindow.x, mainWindow.y, mainWindow.width, mainWindow.height, NULL, 0, hInstance, NULL);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
// This code is based roughly on tutorial code present at http://zetcode.com/gui/winapi/
Further reading
The builtin set of window classes are rather limited, so you might be curious as to how you can define your own window classes ("Controls") using the Windows API, see the articles below:
Custom Controls in Win32 API: The Basics (Code Project)
The WINE emulator source serves as a good example of how the Windows API could be implemented, and how you can make your own window classes that imitate the behavior of builtin classes.
Zetcode.com's tutorials
NOTE: I originally intended this post to cover the creation of dialogs programmatically. Due to a mistake on my part I didn't realize that you can't just "show" a window as a dialog. Unfortunately I wasn't able to get the setup mentioned by Raymond Chen working. Even looking at WINE's source, it's not super clear.
Take a look at this toolkit that describes how to create dialogs without resource files.
It's in WTL. However, I'm sure you can pick apart the internals to achieve the same thing using the Win32 API directly.
Here you can find how to use Windows API dialogs without using resource files.
The Windows API (only the C Win32 API, no MFC) tutorial:
Windows API tutorial
Try to search MSDN for "dialog templates in memory".
See this for example: Dialog Boxes