Win32 - How Do I Intercept and Process Keyboard Input? - c

I am trying to create a simple program I can use to wrap console software. I have a basic window with an EDIT component. I know I can use WM_KEYUP and others to intercept keyborad input. I can't seem to discover an effective way to convert any of the parameters of CALLBACK WinProc; whereupon I will be able to complete this portion of my program:
#include <windows.h>
#define IDC_MAIN_EDIT 101
#define WIDTH 800
#define HEIGHT 600
LRESULT CALLBACK WinProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInst,HINSTANCE hPrevInst,LPSTR lpCmdLine,int nShowCmd) {
WNDCLASSEX wClass;
ZeroMemory(&wClass,sizeof(WNDCLASSEX));
wClass.cbSize=sizeof(WNDCLASSEX);
wClass.hbrBackground=(HBRUSH)COLOR_WINDOW;
wClass.hCursor=LoadCursor(NULL,IDC_ARROW);
wClass.hIcon=NULL;
wClass.hIconSm=NULL;
wClass.hInstance=hInst;
wClass.lpfnWndProc=(WNDPROC)WinProc;
wClass.lpszClassName="Window Class";
wClass.lpszMenuName=NULL;
wClass.style=CS_HREDRAW|CS_VREDRAW;
if(!RegisterClassEx(&wClass)) {
int nResult=GetLastError();
MessageBox(NULL,
"Window class creation failed",
"Window Class Failed",
MB_ICONERROR);
}
HWND hWnd=CreateWindowEx(0,
"Window Class",
"Windows application",
WS_OVERLAPPEDWINDOW,
200,
200,
640,
480,
NULL,
NULL,
hInst,
NULL);
if(!hWnd) {
int nResult=GetLastError();
MessageBox(NULL,
"Window creation failed",
"Window Creation Failed",
MB_ICONERROR);
}
ShowWindow(hWnd,nShowCmd);
MSG msg;
ZeroMemory(&msg,sizeof(MSG));
while(GetMessage(&msg,NULL,0,0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WinProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam) {
static HWND hEdit;
switch(msg) {
case WM_DESTROY:
PostQuitMessage(0);
return 0;
break;
case WM_CREATE:
hEdit = CreateWindowEx(WS_EX_CLIENTEDGE,
"EDIT",
"",
WS_CHILD|WS_VISIBLE|ES_MULTILINE|WS_VISIBLE|WS_VSCROLL|ES_MULTILINE,
0,
0,
WIDTH,
HEIGHT,
hWnd,
(HMENU)IDC_MAIN_EDIT,
GetModuleHandle(NULL),
NULL);
HFONT hFont = CreateFont(0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TEXT("Courier New"));
SendMessage(hEdit, WM_SETFONT, (WPARAM)hFont, 0);
SendMessage(hEdit,
WM_SETTEXT,
0,
(LPARAM)"Insert text here...");
break;
case WM_SIZE:
MoveWindow(hEdit, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE);
break;
}
return DefWindowProc(hWnd,msg,wParam,lParam);
}
What I should have said is: I can't seem to discover a way to intercept keyboard input as chars. How can I intercept all normal keyboard input?

To answer your question:
What I should have said is: I can't seem to discover a way to
intercept keyboard input as chars. How can I intercept all normal
keyboard input?
Take a look at this example from Microsoft on how to handle the WM_CHAR message to get the keyboard character input:
Using Keyboard Input
https://msdn.microsoft.com/en-us/library/windows/desktop/ms646268(v=vs.85).aspx
#define BUFSIZE 65535
#define SHIFTED 0x8000
LONG APIENTRY MainWndProc(HWND hwndMain, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
HDC hdc; // handle to device context
TEXTMETRIC tm; // structure for text metrics
static DWORD dwCharX; // average width of characters
static DWORD dwCharY; // height of characters
static DWORD dwClientX; // width of client area
static DWORD dwClientY; // height of client area
static DWORD dwLineLen; // line length
static DWORD dwLines; // text lines in client area
static int nCaretPosX = 0; // horizontal position of caret
static int nCaretPosY = 0; // vertical position of caret
static int nCharWidth = 0; // width of a character
static int cch = 0; // characters in buffer
static int nCurChar = 0; // index of current character
static PTCHAR pchInputBuf; // input buffer
int i, j; // loop counters
int cCR = 0; // count of carriage returns
int nCRIndex = 0; // index of last carriage return
int nVirtKey; // virtual-key code
TCHAR szBuf[128]; // temporary buffer
TCHAR ch; // current character
PAINTSTRUCT ps; // required by BeginPaint
RECT rc; // output rectangle for DrawText
SIZE sz; // string dimensions
COLORREF crPrevText; // previous text color
COLORREF crPrevBk; // previous background color
size_t * pcch;
HRESULT hResult;
switch (uMsg)
{
case WM_CREATE:
// Get the metrics of the current font.
hdc = GetDC(hwndMain);
GetTextMetrics(hdc, &tm);
ReleaseDC(hwndMain, hdc);
// Save the average character width and height.
dwCharX = tm.tmAveCharWidth;
dwCharY = tm.tmHeight;
// Allocate a buffer to store keyboard input.
pchInputBuf = (LPTSTR) GlobalAlloc(GPTR,
BUFSIZE * sizeof(TCHAR));
return 0;
case WM_SIZE:
// Save the new width and height of the client area.
dwClientX = LOWORD(lParam);
dwClientY = HIWORD(lParam);
// Calculate the maximum width of a line and the
// maximum number of lines in the client area.
dwLineLen = dwClientX - dwCharX;
dwLines = dwClientY / dwCharY;
break;
case WM_SETFOCUS:
// Create, position, and display the caret when the
// window receives the keyboard focus.
CreateCaret(hwndMain, (HBITMAP) 1, 0, dwCharY);
SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);
ShowCaret(hwndMain);
break;
case WM_KILLFOCUS:
// Hide and destroy the caret when the window loses the
// keyboard focus.
HideCaret(hwndMain);
DestroyCaret();
break;
case WM_CHAR:
// check if current location is close enough to the
// end of the buffer that a buffer overflow may
// occur. If so, add null and display contents.
if (cch > BUFSIZE-5)
{
pchInputBuf[cch] = 0x00;
SendMessage(hwndMain, WM_PAINT, 0, 0);
}
switch (wParam)
{
case 0x08: // backspace
case 0x0A: // linefeed
case 0x1B: // escape
MessageBeep((UINT) -1);
return 0;
case 0x09: // tab
// Convert tabs to four consecutive spaces.
for (i = 0; i < 4; i++)
SendMessage(hwndMain, WM_CHAR, 0x20, 0);
return 0;
case 0x0D: // carriage return
// Record the carriage return and position the
// caret at the beginning of the new line.
pchInputBuf[cch++] = 0x0D;
nCaretPosX = 0;
nCaretPosY += 1;
break;
default: // displayable character
ch = (TCHAR) wParam;
HideCaret(hwndMain);
// Retrieve the character's width and output
// the character.
hdc = GetDC(hwndMain);
GetCharWidth32(hdc, (UINT) wParam, (UINT) wParam,
&nCharWidth);
TextOut(hdc, nCaretPosX, nCaretPosY * dwCharY,
&ch, 1);
ReleaseDC(hwndMain, hdc);
// Store the character in the buffer.
pchInputBuf[cch++] = ch;
// Calculate the new horizontal position of the
// caret. If the position exceeds the maximum,
// insert a carriage return and move the caret
// to the beginning of the next line.
nCaretPosX += nCharWidth;
if ((DWORD) nCaretPosX > dwLineLen)
{
nCaretPosX = 0;
pchInputBuf[cch++] = 0x0D;
++nCaretPosY;
}
nCurChar = cch;
ShowCaret(hwndMain);
break;
}
SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);
break;
case WM_KEYDOWN:
switch (wParam)
{
case VK_LEFT: // LEFT ARROW
// The caret can move only to the beginning of
// the current line.
if (nCaretPosX > 0)
{
HideCaret(hwndMain);
// Retrieve the character to the left of
// the caret, calculate the character's
// width, then subtract the width from the
// current horizontal position of the caret
// to obtain the new position.
ch = pchInputBuf[--nCurChar];
hdc = GetDC(hwndMain);
GetCharWidth32(hdc, ch, ch, &nCharWidth);
ReleaseDC(hwndMain, hdc);
nCaretPosX = max(nCaretPosX - nCharWidth,
0);
ShowCaret(hwndMain);
}
break;
case VK_RIGHT: // RIGHT ARROW
// Caret moves to the right or, when a carriage
// return is encountered, to the beginning of
// the next line.
if (nCurChar < cch)
{
HideCaret(hwndMain);
// Retrieve the character to the right of
// the caret. If it's a carriage return,
// position the caret at the beginning of
// the next line.
ch = pchInputBuf[nCurChar];
if (ch == 0x0D)
{
nCaretPosX = 0;
nCaretPosY++;
}
// If the character isn't a carriage
// return, check to see whether the SHIFT
// key is down. If it is, invert the text
// colors and output the character.
else
{
hdc = GetDC(hwndMain);
nVirtKey = GetKeyState(VK_SHIFT);
if (nVirtKey & SHIFTED)
{
crPrevText = SetTextColor(hdc,
RGB(255, 255, 255));
crPrevBk = SetBkColor(hdc,
RGB(0,0,0));
TextOut(hdc, nCaretPosX,
nCaretPosY * dwCharY,
&ch, 1);
SetTextColor(hdc, crPrevText);
SetBkColor(hdc, crPrevBk);
}
// Get the width of the character and
// calculate the new horizontal
// position of the caret.
GetCharWidth32(hdc, ch, ch, &nCharWidth);
ReleaseDC(hwndMain, hdc);
nCaretPosX = nCaretPosX + nCharWidth;
}
nCurChar++;
ShowCaret(hwndMain);
break;
}
break;
case VK_UP: // UP ARROW
case VK_DOWN: // DOWN ARROW
MessageBeep((UINT) -1);
return 0;
case VK_HOME: // HOME
// Set the caret's position to the upper left
// corner of the client area.
nCaretPosX = nCaretPosY = 0;
nCurChar = 0;
break;
case VK_END: // END
// Move the caret to the end of the text.
for (i=0; i < cch; i++)
{
// Count the carriage returns and save the
// index of the last one.
if (pchInputBuf[i] == 0x0D)
{
cCR++;
nCRIndex = i + 1;
}
}
nCaretPosY = cCR;
// Copy all text between the last carriage
// return and the end of the keyboard input
// buffer to a temporary buffer.
for (i = nCRIndex, j = 0; i < cch; i++, j++)
szBuf[j] = pchInputBuf[i];
szBuf[j] = TEXT('\0');
// Retrieve the text extent and use it
// to set the horizontal position of the
// caret.
hdc = GetDC(hwndMain);
hResult = StringCchLength(szBuf, 128, pcch);
if (FAILED(hResult))
{
// TODO: write error handler
}
GetTextExtentPoint32(hdc, szBuf, *pcch,
&sz);
nCaretPosX = sz.cx;
ReleaseDC(hwndMain, hdc);
nCurChar = cch;
break;
default:
break;
}
SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);
break;
case WM_PAINT:
if (cch == 0) // nothing in input buffer
break;
hdc = BeginPaint(hwndMain, &ps);
HideCaret(hwndMain);
// Set the clipping rectangle, and then draw the text
// into it.
SetRect(&rc, 0, 0, dwLineLen, dwClientY);
DrawText(hdc, pchInputBuf, -1, &rc, DT_LEFT);
ShowCaret(hwndMain);
EndPaint(hwndMain, &ps);
break;
// Process other messages.
case WM_DESTROY:
PostQuitMessage(0);
// Free the input buffer.
GlobalFree((HGLOBAL) pchInputBuf);
UnregisterHotKey(hwndMain, 0xAAAA);
break;
default:
return DefWindowProc(hwndMain, uMsg, wParam, lParam);
}
return NULL;
}

Related

Why does the Sleep() function prevent the entire loop from working?

The goal is to create a program that logs keystrokes and writes it into a text file. Currently, just tapping a key will write that key a hundred times so I'm trying to slow it down a bit.
However, using Sleep() will prevent this whole code from doing anything at all unless I use Sleep(0) (which, as I understand, means "Do not let lower priority threads run").
Code:
// Subconsole is Windows so the running app is not visible to a certain someone
int __stdcall WinMain(_In_ HINSTANCE hinstance, _In_opt_ HINSTANCE hprevinstance, _In_ LPSTR lpcmdline, _In_ int ncmdshow)
{
FILE* write;
char running = 1;
fopen_s(&write, "typelog.txt", "w");
while (running)
{
_Bool keytoggle;
char key;
// Go from A to Z and see if the key for that was pressed
for (int i = 0x41; i < 0x5A; i++)
{
// Is the highest order bit for GetAsyncKeyState a 1 (is the key down)
keytoggle = (GetAsyncKeyState(i) & (1 << 15)) != 0;
if (keytoggle)
{
key = i; // save the key that was pressed
break;
}
}
// If the key was pressed, write it, otherwise write a space
if (keytoggle)
{
if (write)
fprintf(write, "%c", key);
}
else
{
if (write)
fprintf(write, " ");
}
// Sleep for like, just one millisecond please
Sleep(1);
}
return 0;
}
I have heard that using Sleep, even for a 1ms, can be extended to 20ms because of the system timer. Is that the case? Even if it was, why would the code not be executed at all?
I've searched for an hour or so and found nothing. If you can help it'd be great.
With debugging, the problem is your txt handle is not closed when calling Sleep(1). You can use Message-Only Windows and Raw Input to achieve your goal. For example:
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, HWND_MESSAGE, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
RawInput(hWnd);
return TRUE;
}
and
#define BUFFER 512
HRESULT ShowRawInputInfo(LPARAM lParam)
{
UINT dwSize = 0;
HRESULT hResult;
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));
LPBYTE lpb = new BYTE[dwSize];
if (lpb == NULL)
{
return 0;
}
if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize)
OutputDebugString(TEXT("GetRawInputData does not return correct size !\n"));
RAWINPUT* raw = (RAWINPUT*)lpb;
WCHAR szTempOutput[BUFFER];
if (raw->header.dwType == RIM_TYPEKEYBOARD)
{
hResult = StringCchPrintf(szTempOutput, BUFFER,
TEXT(" Kbd: make=%04x Flags:%04x Reserved:%04x ExtraInformation:%08x, msg=%04x VK=%04x \n"),
raw->data.keyboard.MakeCode,
raw->data.keyboard.Flags,
raw->data.keyboard.Reserved,
raw->data.keyboard.ExtraInformation,
raw->data.keyboard.Message,
raw->data.keyboard.VKey);
if (FAILED(hResult))
{
// TODO: write error handler
}
OutputDebugString(szTempOutput);
}
else if (raw->header.dwType == RIM_TYPEMOUSE)
{
hResult = StringCchPrintf(szTempOutput, BUFFER,
TEXT("Mouse: usFlags=%04x ulButtons=%04x usButtonFlags=%04x usButtonData=%04x ulRawButtons=%04x lLastX=%04x lLastY=%04x ulExtraInformation=%04x\r\n"),
raw->data.mouse.usFlags,
raw->data.mouse.ulButtons,
raw->data.mouse.usButtonFlags,
raw->data.mouse.usButtonData,
raw->data.mouse.ulRawButtons,
raw->data.mouse.lLastX,
raw->data.mouse.lLastY,
raw->data.mouse.ulExtraInformation);
if (FAILED(hResult))
{
// TODO: write error handler
}
OutputDebugString(szTempOutput);
}
delete[] lpb;
return 0;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
DWORD dwStyleOfStaticText = 0;
HWND hBmp2 = NULL;
WORD reason = 0;
switch (message)
{
case WM_INPUT:
{
ShowRawInputInfo(lParam);
break;
}
case WM_KEYDOWN:
WCHAR szTempOutput[512];
StringCchPrintf(szTempOutput, 512,
TEXT(" KeyValue=%04x\n"), wParam);
OutputDebugString(szTempOutput);
//PostMessage(hWnd, WM_COMMAND, KILLTHEWIN, 0);// hope it serializes message
//PostQuitMessage(0);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
Edit: Or Hook

Detect USB drive insertion in C (Windows)

I tried looking around and found a few solutions to detect a USB drive insertion, but none that I found were actually working in C.
I wanted to ask, how do I approach this problem?
What is the idea behind the detection process (Like, how is it done) ?
Thank you in advance! :)
The example at link https://msdn.microsoft.com/en-us/library/windows/desktop/aa363432(v=vs.85).aspx, given by Weather Vane, works in plain C, as I said in comments, with simple modifications.
Below there is the working modified code.
#define UNICODE 1
#define _UNICODE 1
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#include <dbt.h>
#pragma comment(lib, "user32.lib" )
#pragma comment(lib, "Shell32.lib" )
void Main_OnDeviceChange( HWND hwnd, WPARAM wParam, LPARAM lParam );
char FirstDriveFromMask( ULONG unitmask ); //prototype
// This GUID is for all USB serial host PnP drivers, but you can replace it
// with any valid device class guid.
GUID WceusbshGUID = { 0x25dbce51, 0x6c8f, 0x4a72,
0x8a,0x6d,0xb5,0x4c,0x2b,0x4f,0xc8,0x35 };
// For informational messages and window titles
PWSTR g_pszAppName;
// Forward declarations
void OutputMessage(HWND hOutWnd, WPARAM wParam, LPARAM lParam);
void ErrorHandler(LPTSTR lpszFunction);
//
// DoRegisterDeviceInterfaceToHwnd
//
BOOL DoRegisterDeviceInterfaceToHwnd(
IN GUID InterfaceClassGuid,
IN HWND hWnd,
OUT HDEVNOTIFY *hDeviceNotify
)
// Routine Description:
// Registers an HWND for notification of changes in the device interfaces
// for the specified interface class GUID.
// Parameters:
// InterfaceClassGuid - The interface class GUID for the device
// interfaces.
// hWnd - Window handle to receive notifications.
// hDeviceNotify - Receives the device notification handle. On failure,
// this value is NULL.
// Return Value:
// If the function succeeds, the return value is TRUE.
// If the function fails, the return value is FALSE.
// Note:
// RegisterDeviceNotification also allows a service handle be used,
// so a similar wrapper function to this one supporting that scenario
// could be made from this template.
{
DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) );
NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
NotificationFilter.dbcc_classguid = InterfaceClassGuid;
*hDeviceNotify = RegisterDeviceNotification(
hWnd, // events recipient
&NotificationFilter, // type of device
DEVICE_NOTIFY_WINDOW_HANDLE // type of recipient handle
);
if ( NULL == *hDeviceNotify )
{
ErrorHandler(TEXT("RegisterDeviceNotification"));
return FALSE;
}
return TRUE;
}
//
// MessagePump
//
void MessagePump(
HWND hWnd
)
// Routine Description:
// Simple main thread message pump.
//
// Parameters:
// hWnd - handle to the window whose messages are being dispatched
// Return Value:
// None.
{
MSG msg;
int retVal;
// Get all messages for any window that belongs to this thread,
// without any filtering. Potential optimization could be
// obtained via use of filter values if desired.
while( (retVal = GetMessage(&msg, NULL, 0, 0)) != 0 )
{
if ( retVal == -1 )
{
ErrorHandler(TEXT("GetMessage"));
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
//
// WinProcCallback
//
INT_PTR WINAPI WinProcCallback(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam
)
// Routine Description:
// Simple Windows callback for handling messages.
// This is where all the work is done because the example
// is using a window to process messages. This logic would be handled
// differently if registering a service instead of a window.
// Parameters:
// hWnd - the window handle being registered for events.
// message - the message being interpreted.
// wParam and lParam - extended information provided to this
// callback by the message sender.
// For more information regarding these parameters and return value,
// see the documentation for WNDCLASSEX and CreateWindowEx.
{
LRESULT lRet = 1;
static HDEVNOTIFY hDeviceNotify;
static HWND hEditWnd;
static ULONGLONG msgCount = 0;
switch (message)
{
case WM_CREATE:
//
// This is the actual registration., In this example, registration
// should happen only once, at application startup when the window
// is created.
//
// If you were using a service, you would put this in your main code
// path as part of your service initialization.
//
if ( ! DoRegisterDeviceInterfaceToHwnd(
WceusbshGUID,
hWnd,
&hDeviceNotify) )
{
// Terminate on failure.
ErrorHandler(TEXT("DoRegisterDeviceInterfaceToHwnd"));
ExitProcess(1);
}
//
// Make the child window for output.
//
hEditWnd = CreateWindow(TEXT("EDIT"),// predefined class
NULL, // no window title
WS_CHILD | WS_VISIBLE | WS_VSCROLL |
ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL,
0, 0, 0, 0, // set size in WM_SIZE message
hWnd, // parent window
(HMENU)1, // edit control ID
(HINSTANCE) GetWindowLong(hWnd, GWL_HINSTANCE),
NULL); // pointer not needed
if ( hEditWnd == NULL )
{
// Terminate on failure.
ErrorHandler(TEXT("CreateWindow: Edit Control"));
ExitProcess(1);
}
// Add text to the window.
SendMessage(hEditWnd, WM_SETTEXT, 0,
(LPARAM)TEXT("Registered for USB device notification...\n"));
break;
case WM_SETFOCUS:
SetFocus(hEditWnd);
break;
case WM_SIZE:
// Make the edit control the size of the window's client area.
MoveWindow(hEditWnd,
0, 0, // starting x- and y-coordinates
LOWORD(lParam), // width of client area
HIWORD(lParam), // height of client area
TRUE); // repaint window
break;
case WM_DEVICECHANGE:
{
//
// This is the actual message from the interface via Windows messaging.
// This code includes some additional decoding for this particular device type
// and some common validation checks.
//
// Note that not all devices utilize these optional parameters in the same
// way. Refer to the extended information for your particular device type
// specified by your GUID.
//
PDEV_BROADCAST_DEVICEINTERFACE b = (PDEV_BROADCAST_DEVICEINTERFACE) lParam;
(void)b;
TCHAR strBuff[256];
Main_OnDeviceChange(hEditWnd, wParam, lParam);
// Output some messages to the window.
switch (wParam)
{
case DBT_DEVICEARRIVAL:
msgCount++;
StringCchPrintf(
strBuff, 256,
TEXT("Message %d: DBT_DEVICEARRIVAL\n"), msgCount);
break;
case DBT_DEVICEREMOVECOMPLETE:
msgCount++;
StringCchPrintf(
strBuff, 256,
TEXT("Message %d: DBT_DEVICEREMOVECOMPLETE\n"), msgCount);
break;
case DBT_DEVNODES_CHANGED:
msgCount++;
StringCchPrintf(
strBuff, 256,
TEXT("Message %d: DBT_DEVNODES_CHANGED\n"), msgCount);
break;
default:
msgCount++;
StringCchPrintf(
strBuff, 256,
TEXT("Message %d: WM_DEVICECHANGE message received, value %d unhandled.\n"),
msgCount, wParam);
break;
}
OutputMessage(hEditWnd, wParam, (LPARAM)strBuff);
}
break;
case WM_CLOSE:
if ( ! UnregisterDeviceNotification(hDeviceNotify) )
{
ErrorHandler(TEXT("UnregisterDeviceNotification"));
}
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
// Send all other messages on to the default windows handler.
lRet = DefWindowProc(hWnd, message, wParam, lParam);
break;
}
return lRet;
}
#define WND_CLASS_NAME TEXT("SampleAppWindowClass")
//
// InitWindowClass
//
BOOL InitWindowClass(void)
// Routine Description:
// Simple wrapper to initialize and register a window class.
// Parameters:
// None
// Return Value:
// TRUE on success, FALSE on failure.
// Note:
// wndClass.lpfnWndProc and wndClass.lpszClassName are the
// important unique values used with CreateWindowEx and the
// Windows message pump.
{
WNDCLASSEX wndClass;
wndClass.cbSize = sizeof(WNDCLASSEX);
wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wndClass.hInstance = (HINSTANCE)(GetModuleHandle(0));
wndClass.lpfnWndProc = (WNDPROC)(WinProcCallback);
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hIcon = LoadIcon(0,IDI_APPLICATION);
wndClass.hbrBackground = CreateSolidBrush(RGB(192,192,192));
wndClass.hCursor = LoadCursor(0, IDC_ARROW);
wndClass.lpszClassName = WND_CLASS_NAME;
wndClass.lpszMenuName = NULL;
wndClass.hIconSm = wndClass.hIcon;
if ( ! RegisterClassEx(&wndClass) )
{
ErrorHandler(TEXT("RegisterClassEx"));
return FALSE;
}
return TRUE;
}
//
// main
//
int __stdcall _tWinMain(
HINSTANCE hInstanceExe,
HINSTANCE hInst, // should not reference this parameter
PTSTR lpstrCmdLine,
int nCmdShow
)
{
//
// To enable a console project to compile this code, set
// Project->Properties->Linker->System->Subsystem: Windows.
//
int nArgC = 0;
PWSTR* ppArgV = CommandLineToArgvW(lpstrCmdLine, &nArgC);
g_pszAppName = ppArgV[0];
if ( ! InitWindowClass() )
{
// InitWindowClass displays any errors
return -1;
}
// Main app window
HWND hWnd = CreateWindowEx(
WS_EX_CLIENTEDGE | WS_EX_APPWINDOW,
WND_CLASS_NAME,
g_pszAppName,
WS_OVERLAPPEDWINDOW, // style
CW_USEDEFAULT, 0,
640, 480,
NULL, NULL,
hInstanceExe,
NULL);
if ( hWnd == NULL )
{
ErrorHandler(TEXT("CreateWindowEx: main appwindow hWnd"));
return -1;
}
// Actually draw the window.
ShowWindow(hWnd, SW_SHOWNORMAL);
UpdateWindow(hWnd);
// The message pump loops until the window is destroyed.
MessagePump(hWnd);
return 1;
}
//
// OutputMessage
//
void OutputMessage(
HWND hOutWnd,
WPARAM wParam,
LPARAM lParam
)
// Routine Description:
// Support routine.
// Send text to the output window, scrolling if necessary.
// Parameters:
// hOutWnd - Handle to the output window.
// wParam - Standard windows message code, not used.
// lParam - String message to send to the window.
// Return Value:
// None
// Note:
// This routine assumes the output window is an edit control
// with vertical scrolling enabled.
// This routine has no error checking.
{
LRESULT lResult;
LONG bufferLen;
LONG numLines;
LONG firstVis;
// Make writable and turn off redraw.
lResult = SendMessage(hOutWnd, EM_SETREADONLY, FALSE, 0L);
lResult = SendMessage(hOutWnd, WM_SETREDRAW, FALSE, 0L);
// Obtain current text length in the window.
bufferLen = SendMessage (hOutWnd, WM_GETTEXTLENGTH, 0, 0L);
numLines = SendMessage (hOutWnd, EM_GETLINECOUNT, 0, 0L);
firstVis = SendMessage (hOutWnd, EM_GETFIRSTVISIBLELINE, 0, 0L);
lResult = SendMessage (hOutWnd, EM_SETSEL, bufferLen, bufferLen);
// Write the new text.
lResult = SendMessage (hOutWnd, EM_REPLACESEL, 0, lParam);
// See whether scrolling is necessary.
if (numLines > (firstVis + 1))
{
int lineLen = 0;
int lineCount = 0;
int charPos;
// Find the last nonblank line.
numLines--;
while(!lineLen)
{
charPos = SendMessage(
hOutWnd, EM_LINEINDEX, (WPARAM)numLines, 0L);
lineLen = SendMessage(
hOutWnd, EM_LINELENGTH, charPos, 0L);
if(!lineLen)
numLines--;
}
// Prevent negative value finding min.
lineCount = numLines - firstVis;
lineCount = (lineCount >= 0) ? lineCount : 0;
// Scroll the window.
lResult = SendMessage(
hOutWnd, EM_LINESCROLL, 0, (LPARAM)lineCount);
}
// Done, make read-only and allow redraw.
lResult = SendMessage(hOutWnd, WM_SETREDRAW, TRUE, 0L);
lResult = SendMessage(hOutWnd, EM_SETREADONLY, TRUE, 0L);
}
//
// ErrorHandler
//
void ErrorHandler(
LPTSTR lpszFunction
)
// Routine Description:
// Support routine.
// Retrieve the system error message for the last-error code
// and pop a modal alert box with usable info.
// Parameters:
// lpszFunction - String containing the function name where
// the error occurred plus any other relevant data you'd
// like to appear in the output.
// Return Value:
// None
// Note:
// This routine is independent of the other windowing routines
// in this application and can be used in a regular console
// application without modification.
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message and exit the process.
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)
+ lstrlen((LPCTSTR)lpszFunction)+40)
* sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, g_pszAppName, MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
/*+##fnc##----------------------------------------------------------------*//*!
\brief Main_OnDeviceChange
\date Created on Sun Sep 10 15:10:10 2017
\date Modified on Sun Sep 10 15:10:10 2017
\*//*-##fnc##----------------------------------------------------------------*/
void Main_OnDeviceChange(HWND hwnd, WPARAM wParam, LPARAM lParam)
{
PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
TCHAR szMsg[80];
switch (wParam)
{
case DBT_DEVICEARRIVAL:
// Check whether a CD or DVD was inserted into a drive.
if (lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)
{
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
if (lpdbv->dbcv_flags & DBTF_MEDIA)
{
StringCchPrintf(szMsg, sizeof(szMsg) / sizeof(szMsg[0]), TEXT("Drive %c: Media has arrived.\n"), FirstDriveFromMask(lpdbv->dbcv_unitmask));
//MessageBox( hwnd, szMsg, TEXT("WM_DEVICECHANGE"), MB_OK );
}
else
{
StringCchPrintf(szMsg, sizeof(szMsg) / sizeof(szMsg[0]), TEXT("Assigned drive letter '%c'\n"), FirstDriveFromMask(lpdbv->dbcv_unitmask));
}
OutputMessage(hwnd, wParam, (LPARAM)szMsg);
}
break;
case DBT_DEVICEREMOVECOMPLETE:
// Check whether a CD or DVD was removed from a drive.
if (lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)
{
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
if (lpdbv->dbcv_flags & DBTF_MEDIA)
{
StringCchPrintf(szMsg, sizeof(szMsg) / sizeof(szMsg[0]), TEXT("Drive %c: Media was removed.\n"), FirstDriveFromMask(lpdbv->dbcv_unitmask));
//MessageBox( hwnd, szMsg, TEXT("WM_DEVICECHANGE" ), MB_OK );
}
else
{
StringCchPrintf(szMsg, sizeof(szMsg) / sizeof(szMsg[0]), TEXT("Disconnected drive '%c'\n"), FirstDriveFromMask(lpdbv->dbcv_unitmask));
}
OutputMessage(hwnd, wParam, (LPARAM)szMsg);
}
break;
default:
/*
Process other WM_DEVICECHANGE notifications for other
devices or reasons.
*/
;
}
}
/*------------------------------------------------------------------
FirstDriveFromMask( unitmask )
Description
Finds the first valid drive letter from a mask of drive letters.
The mask must be in the format bit 0 = A, bit 1 = B, bit 2 = C,
and so on. A valid drive letter is defined when the
corresponding bit is set to 1.
Returns the first drive letter that was found.
--------------------------------------------------------------------*/
char FirstDriveFromMask( ULONG unitmask )
{
char i;
for (i = 0; i < 26; ++i)
{
if (unitmask & 0x1)
break;
unitmask = unitmask >> 1;
}
return( i + 'A' );
}
Basically remove reinterpret_cast to C casts. I.e.:
wndClass.hInstance = reinterpret_cast<HINSTANCE>(GetModuleHandle(0));
to
wndClass.hInstance = (HINSTANCE)(GetModuleHandle(0));
And add unused parameters name in functions definition (that is not allowed in standard C). I.e. change from:
int __stdcall _tWinMain(
HINSTANCE hInstanceExe,
HINSTANCE, // should not reference this parameter
PTSTR lpstrCmdLine,
int nCmdShow
)
to:
int __stdcall _tWinMain(
HINSTANCE hInstanceExe,
HINSTANCE hInst, // you **must define this parameter** even if it's not referenced
PTSTR lpstrCmdLine,
int nCmdShow
)
These simple modifications allow the use of almost all MS samples under plain-C compilers.
I have also added volume info.
To explain here in detail how the device notification framework works is just a waste of time. The MS documentation is complete and exhaustive, you can find all information on MSDN.
The translation I made give you the opportunity to study and test on your development environment in plain C, and this will allow to make experimentation.
Anyway the very basic essence is: the application (your program) registers itself with the notification server, that in turn, from now on until you unregister it, send all windows OS notification messages to your application. Each notification carries specific info data in specialized structures.
The full set of structure supplied with each notification (documented on MSDN) gives you indeep details on the type of change.

How can I remove text after clicking?

I'm making the prototype for my own visual novel game engine.
while (i < 5)
{
switch (iMessage)
{
case WM_LBUTTONDOWN:
{
//InvalidateRect(hWnd, NULL, TRUE);
HDC hdc;
hdc = GetDC(hWnd);
_wsetlocale(LC_ALL, L"Korean");
ReadScn(buf);
//MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, char, strlen(buf), buf3, 256);
CharToWChar(buf, buf2);
TextOut(hdc, 320, 300, buf2, lstrlen(buf2)); //읽어들여서 출력함.
//TCHAR*str = TEXT("beautiful korea");
//TextOut(hdc, 320, 240, str, lstrlen(str));
ReleaseDC(hWnd, hdc);
i++;
return 0;
}
}
I wrote 5 lines of text to scn.txt. Then the program prints the texts to a window, but the text lines are overlapped.
How can I remove the previous text after clicking and print new text line?
The correct way to handle this is to NOT draw anything on the window from inside of the WM_LBUTTONDOWN message handler at all. That logic belongs in the WM_PAINT message handler instead. Have the WM_LBUTTONDOWN handler save the current line of text to a variable and then InvalidateRect() the window to trigger a repaint. The WM_PAINT handler can then draw the current line whenever the window needs to be painted (which can happen more than once between button clicks).
Try this:
case WM_LBUTTONDOWN:
{
_wsetlocale(LC_ALL, L"Korean");
ReadScn(buf); //read text from scn.txt and keep it in buf line by line.
CharToWChar(buf, buf2); //convert char into wChar.
InvalidateRect(hwnd, NULL, TRUE); //trigger a repaint
return 0;
}
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
TextOut(hdc, 320, 300, buf2, lstrlen(buf2));
EndPaint(hwnd, &ps);
return 0;
}

What's going on in my custom list view control that leads to rows either partially or fully not being redrawn when scrolling?

I'm building a custom listview control as the standard comctl32.dll one does not adequately fit my needs. Things seem to be going well for what I have so far, except for scrolling.
At first, things look like this (under wine, but real Windows is affected too);
The form of corruption changes depending on the type of scrolling used. If I scroll using the mouse wheel, every few rows is corrupted:
And if I scroll by dragging the thumb, this happens:
In both cases, clicking somewhere will redraw everything, and the corruption goes away.
I'm not really sure what I'm doing wrong here.
Here's the code; I will explain how it works below:
// 19 october 2014
#define UNICODE
#define _UNICODE
#define STRICT
#define STRICT_TYPED_ITEMIDS
// get Windows version right; right now Windows XP
#define WINVER 0x0501
#define _WIN32_WINNT 0x0501
#define _WIN32_WINDOWS 0x0501 /* according to Microsoft's winperf.h */
#define _WIN32_IE 0x0600 /* according to Microsoft's sdkddkver.h */
#define NTDDI_VERSION 0x05010000 /* according to Microsoft's sdkddkver.h */
#include <windows.h>
#include <commctrl.h>
#include <stdint.h>
#include <uxtheme.h>
#include <string.h>
#include <wchar.h>
#include <windowsx.h>
#include <vsstyle.h>
#include <vssym32.h>
// #qo LIBS: user32 kernel32 gdi32 comctl32
// TODO
// - http://blogs.msdn.com/b/oldnewthing/archive/2003/09/09/54826.aspx (relies on the integrality parts? IDK)
// - might want to http://blogs.msdn.com/b/oldnewthing/archive/2003/09/17/54944.aspx instead
// - http://msdn.microsoft.com/en-us/library/windows/desktop/bb775574%28v=vs.85%29.aspx
// - hscroll (harder)
// - keyboard navigation
// - mousewheel navigation
#define tableWindowClass L"gouitable"
struct table {
HWND hwnd;
HFONT defaultFont;
HFONT font;
intptr_t selected;
intptr_t count;
intptr_t firstVisible;
intptr_t pagesize; // in rows
int wheelCarry;
HWND header;
int headerHeight;
intptr_t nColumns;
HIMAGELIST imagelist;
int imagelistHeight;
};
static LONG rowHeight(struct table *t)
{
HFONT thisfont, prevfont;
TEXTMETRICW tm;
HDC dc;
LONG ret;
dc = GetDC(t->hwnd);
if (dc == NULL)
abort();
thisfont = t->font; // in case WM_SETFONT happens before we return
prevfont = (HFONT) SelectObject(dc, thisfont);
if (prevfont == NULL)
abort();
if (GetTextMetricsW(dc, &tm) == 0)
abort();
if (SelectObject(dc, prevfont) != (HGDIOBJ) (thisfont))
abort();
if (ReleaseDC(t->hwnd, dc) == 0)
abort();
ret = tm.tmHeight;
if (ret < t->imagelistHeight)
ret = t->imagelistHeight;
return ret;
}
static void redrawAll(struct table *t)
{
if (InvalidateRect(t->hwnd, NULL, TRUE) == 0)
abort();
if (UpdateWindow(t->hwnd) == 0)
abort();
}
static RECT realClientRect(struct table *t)
{
RECT r;
if (GetClientRect(t->hwnd, &r) == 0)
abort();
r.top += t->headerHeight;
return r;
}
static void recomputeHScroll(struct table *t)
{
HDITEMW item;
intptr_t i;
int width = 0;
RECT r;
SCROLLINFO si;
// TODO count dividers
for (i = 0; i < t->nColumns; i++) {
ZeroMemory(&item, sizeof (HDITEMW));
item.mask = HDI_WIDTH;
if (SendMessageW(t->header, HDM_GETITEM, (WPARAM) i, (LPARAM) (&item)) == FALSE)
abort();
width += item.cxy;
}
if (GetClientRect(t->hwnd, &r) == 0)
abort();
ZeroMemory(&si, sizeof (SCROLLINFO));
si.cbSize = sizeof (SCROLLINFO);
si.fMask = SIF_PAGE | SIF_RANGE;
si.nPage = r.right - r.left;
si.nMin = 0;
si.nMax = width - 1; // - 1 because endpoints inclusive
SetScrollInfo(t->hwnd, SB_HORZ, &si, TRUE);
}
static void finishSelect(struct table *t)
{
if (t->selected < 0)
t->selected = 0;
if (t->selected >= t->count)
t->selected = t->count - 1;
// TODO update only the old and new selected items
redrawAll(t);
// TODO scroll to the selected item if it's not entirely visible
}
static void keySelect(struct table *t, WPARAM wParam, LPARAM lParam)
{
// TODO figure out correct behavior with nothing selected
if (t->count == 0) // don't try to do anything if there's nothing to do
return;
switch (wParam) {
case VK_UP:
t->selected--;
break;
case VK_DOWN:
t->selected++;
break;
case VK_PRIOR:
t->selected -= t->pagesize;
break;
case VK_NEXT:
t->selected += t->pagesize;
break;
case VK_HOME:
t->selected = 0;
break;
case VK_END:
t->selected = t->count - 1;
break;
default:
// don't touch anything
return;
}
finishSelect(t);
}
static void selectItem(struct table *t, WPARAM wParam, LPARAM lParam)
{
int x, y;
LONG h;
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
h = rowHeight(t);
y += t->firstVisible * h;
y -= t->headerHeight;
y /= h;
t->selected = y;
if (t->selected >= t->count)
t->selected = -1;
finishSelect(t);
}
// TODO on initial show the items are not arranged properly
// TODO the lowest visible row does not redraw properly after scrolling
// TODO the row behind the header bar does not redraw properly after scrolling
static void vscrollto(struct table *t, intptr_t newpos)
{
SCROLLINFO si;
RECT scrollArea;
if (newpos < 0)
newpos = 0;
if (newpos > (t->count - t->pagesize))
newpos = (t->count - t->pagesize);
scrollArea = realClientRect(t);
// negative because ScrollWindowEx() is "backwards"
if (ScrollWindowEx(t->hwnd, 0, (-(newpos - t->firstVisible)) * rowHeight(t),
&scrollArea, &scrollArea, NULL, NULL,
SW_ERASE | SW_INVALIDATE) == ERROR)
abort();
t->firstVisible = newpos;
ZeroMemory(&si, sizeof (SCROLLINFO));
si.cbSize = sizeof (SCROLLINFO);
si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE;
si.nPage = t->pagesize;
si.nMin = 0;
si.nMax = t->count - 1; // nMax is inclusive
si.nPos = t->firstVisible;
SetScrollInfo(t->hwnd, SB_VERT, &si, TRUE);
}
static void vscrollby(struct table *t, intptr_t n)
{
vscrollto(t, t->firstVisible + n);
}
static void wheelscroll(struct table *t, WPARAM wParam)
{
int delta;
int lines;
UINT scrollAmount;
delta = GET_WHEEL_DELTA_WPARAM(wParam);
if (SystemParametersInfoW(SPI_GETWHEELSCROLLLINES, 0, &scrollAmount, 0) == 0)
abort();
if (scrollAmount == WHEEL_PAGESCROLL)
scrollAmount = t->pagesize;
if (scrollAmount == 0) // no mouse wheel scrolling (or t->pagesize == 0)
return;
// the rest of this is basically http://blogs.msdn.com/b/oldnewthing/archive/2003/08/07/54615.aspx and http://blogs.msdn.com/b/oldnewthing/archive/2003/08/11/54624.aspx
// see those pages for information on subtleties
delta += t->wheelCarry;
lines = delta * ((int) scrollAmount) / WHEEL_DELTA;
t->wheelCarry = delta - lines * WHEEL_DELTA / ((int) scrollAmount);
vscrollby(t, -lines);
}
static void vscroll(struct table *t, WPARAM wParam)
{
SCROLLINFO si;
intptr_t newpos;
ZeroMemory(&si, sizeof (SCROLLINFO));
si.cbSize = sizeof (SCROLLINFO);
si.fMask = SIF_POS | SIF_TRACKPOS;
if (GetScrollInfo(t->hwnd, SB_VERT, &si) == 0)
abort();
newpos = t->firstVisible;
switch (LOWORD(wParam)) {
case SB_TOP:
newpos = 0;
break;
case SB_BOTTOM:
newpos = t->count - t->pagesize;
break;
case SB_LINEUP:
newpos--;
break;
case SB_LINEDOWN:
newpos++;
break;
case SB_PAGEUP:
newpos -= t->pagesize;
break;
case SB_PAGEDOWN:
newpos += t->pagesize;
break;
case SB_THUMBPOSITION:
newpos = (intptr_t) (si.nPos);
break;
case SB_THUMBTRACK:
newpos = (intptr_t) (si.nTrackPos);
}
vscrollto(t, newpos);
}
static void resize(struct table *t)
{
RECT r;
SCROLLINFO si;
HDLAYOUT headerlayout;
WINDOWPOS headerpos;
// do this first so our scrollbar calculations can be correct
if (GetClientRect(t->hwnd, &r) == 0) // use the whole client rect
abort();
headerlayout.prc = &r;
headerlayout.pwpos = &headerpos;
if (SendMessageW(t->header, HDM_LAYOUT, 0, (LPARAM) (&headerlayout)) == FALSE)
abort();
if (SetWindowPos(t->header, headerpos.hwndInsertAfter, headerpos.x, headerpos.y, headerpos.cx, headerpos.cy, headerpos.flags | SWP_SHOWWINDOW) == 0)
abort();
t->headerHeight = headerpos.cy;
// now adjust the scrollbars
r = realClientRect(t);
t->pagesize = (r.bottom - r.top) / rowHeight(t);
ZeroMemory(&si, sizeof (SCROLLINFO));
si.cbSize = sizeof (SCROLLINFO);
si.fMask = SIF_RANGE | SIF_PAGE;
si.nMin = 0;
si.nMax = t->count - 1;
si.nPage = t->pagesize;
SetScrollInfo(t->hwnd, SB_VERT, &si, TRUE);
recomputeHScroll(t);
}
static void drawItems(struct table *t, HDC dc, RECT cliprect)
{
HFONT thisfont, prevfont;
LONG height;
LONG y;
intptr_t i;
RECT controlSize; // for filling the entire selected row
intptr_t first, last;
POINT prevOrigin, prevViewportOrigin;
if (GetClientRect(t->hwnd, &controlSize) == 0)
abort();
height = rowHeight(t);
thisfont = t->font; // in case WM_SETFONT happens before we return
prevfont = (HFONT) SelectObject(dc, thisfont);
if (prevfont == NULL)
abort();
// adjust the clip rect and the window so that (0, 0) is always the first item
// adjust the viewport so that everything is shifted down t->headerHeight pixels
if (OffsetRect(&cliprect, 0, t->firstVisible * height) == 0)
abort();
if (GetWindowOrgEx(dc, &prevOrigin) == 0)
abort();
if (SetWindowOrgEx(dc, prevOrigin.x, prevOrigin.y + (t->firstVisible * height), NULL) == 0)
abort();
if (SetViewportOrgEx(dc, 0, t->headerHeight, &prevViewportOrigin) == 0)
abort();
// see http://blogs.msdn.com/b/oldnewthing/archive/2003/07/29/54591.aspx and http://blogs.msdn.com/b/oldnewthing/archive/2003/07/30/54600.aspx
first = cliprect.top / height;
if (first < 0)
first = 0;
last = (cliprect.bottom + height - 1) / height;
if (last >= t->count)
last = t->count;
y = first * height;
for (i = first; i < last; i++) {
RECT rsel;
HBRUSH background;
int textColor;
WCHAR msg[100];
RECT headeritem;
intptr_t j;
LRESULT xoff;
// TODO verify these two
background = (HBRUSH) (COLOR_WINDOW + 1);
textColor = COLOR_WINDOWTEXT;
if (t->selected == i) {
// these are the colors wine uses (http://source.winehq.org/source/dlls/comctl32/listview.c)
// the two for unfocused are also suggested by http://stackoverflow.com/questions/10428710/windows-forms-inactive-highlight-color
background = (HBRUSH) (COLOR_HIGHLIGHT + 1);
textColor = COLOR_HIGHLIGHTTEXT;
if (GetFocus() != t->hwnd) {
background = (HBRUSH) (COLOR_BTNFACE + 1);
textColor = COLOR_BTNTEXT;
}
}
// first fill the selection rect
rsel.left = controlSize.left;
rsel.top = y;
rsel.right = controlSize.right - controlSize.left;
rsel.bottom = y + height;
if (FillRect(dc, &rsel, background) == 0)
abort();
xoff = SendMessageW(t->header, HDM_GETBITMAPMARGIN, 0, 0);
// now draw the cells
if (SetTextColor(dc, GetSysColor(textColor)) == CLR_INVALID)
abort();
if (SetBkMode(dc, TRANSPARENT) == 0)
abort();
for (j = 0; j < t->nColumns; j++) {
if (SendMessageW(t->header, HDM_GETITEMRECT, (WPARAM) j, (LPARAM) (&headeritem)) == 0)
abort();
if (j == 1) { // TODO
IMAGELISTDRAWPARAMS ip;
ZeroMemory(&ip, sizeof (IMAGELISTDRAWPARAMS));
ip.cbSize = sizeof (IMAGELISTDRAWPARAMS);
ip.himl = t->imagelist;
ip.i = 0;
ip.hdcDst = dc;
ip.x = headeritem.left + xoff;
ip.y = y;
ip.cx = 0; // draw whole image
ip.cy = 0;
ip.xBitmap = 0;
ip.yBitmap = 0;
ip.rgbBk = CLR_NONE;
ip.fStyle = ILD_NORMAL | ILD_SCALE; // TODO alpha-blend; ILD_DPISCALE?
// TODO ILS_ALPHA?
if (ImageList_DrawIndirect(&ip) == 0)
abort();
continue;
}
rsel.left = headeritem.left + xoff;
rsel.top = y;
rsel.right = headeritem.right;
rsel.bottom = y + height;
// TODO vertical center in case the height is less than the icon height?
if (DrawTextExW(dc, msg, wsprintf(msg, L"Item %d", i), &rsel, DT_END_ELLIPSIS | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE, NULL) == 0)
abort();
}
y += height;
}
// reset everything
if (SetViewportOrgEx(dc, prevViewportOrigin.x, prevViewportOrigin.y, NULL) == 0)
abort();
if (SetWindowOrgEx(dc, prevOrigin.x, prevOrigin.y, NULL) == 0)
abort();
if (SelectObject(dc, prevfont) != (HGDIOBJ) (thisfont))
abort();
}
static LRESULT CALLBACK tableWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
struct table *t;
HDC dc;
PAINTSTRUCT ps;
NMHDR *nmhdr = (NMHDR *) lParam;
NMHEADERW *nm = (NMHEADERW *) lParam;
t = (struct table *) GetWindowLongPtrW(hwnd, GWLP_USERDATA);
if (t == NULL) {
// we have to do things this way because creating the header control will fail mysteriously if we create it first thing
// (which is fine; we can get the parent hInstance this way too)
if (uMsg == WM_NCCREATE) {
CREATESTRUCTW *cs = (CREATESTRUCTW *) lParam;
t = (struct table *) malloc(sizeof (struct table));
if (t == NULL)
abort();
ZeroMemory(t, sizeof (struct table));
t->hwnd = hwnd;
// TODO this should be a global
t->defaultFont = (HFONT) GetStockObject(SYSTEM_FONT);
if (t->defaultFont == NULL)
abort();
t->font = t->defaultFont;
t->selected = 5;t->count=100;//TODO
t->header = CreateWindowExW(0,
WC_HEADERW, L"",
// TODO is HOTTRACK needed?
WS_CHILD | HDS_FULLDRAG | HDS_HORZ | HDS_HOTTRACK,
0, 0, 0, 0,
t->hwnd, (HMENU) 100, cs->hInstance, NULL);
if (t->header == NULL)
abort();
{HDITEMW item;
ZeroMemory(&item, sizeof (HDITEMW));
item.mask = HDI_WIDTH | HDI_TEXT | HDI_FORMAT;
item.cxy = 200;
item.pszText = L"Column";
item.fmt = HDF_LEFT | HDF_STRING;
if (SendMessage(t->header, HDM_INSERTITEM, 0, (LPARAM) (&item)) == (LRESULT) (-1))
abort();
ZeroMemory(&item, sizeof (HDITEMW));
item.mask = HDI_WIDTH | HDI_TEXT | HDI_FORMAT;
item.cxy = 150;
item.pszText = L"Column 2";
item.fmt = HDF_LEFT | HDF_STRING;
if (SendMessage(t->header, HDM_INSERTITEM, 1, (LPARAM) (&item)) == (LRESULT) (-1))
abort();
t->nColumns=2;
t->imagelist = ImageList_Create(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), ILC_COLOR32, 1, 1);
if(t->imagelist==NULL)abort();
{
HICON icon;
int unused;
icon = LoadIconW(NULL, IDI_ERROR);
if(icon == NULL)abort();
if (ImageList_AddIcon(t->imagelist, icon) == -1)abort();
if (ImageList_GetIconSize(t->imagelist, &unused, &(t->imagelistHeight)) == 0)abort();
}
}
SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR) t);
}
// even if we did the above, fall through
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
switch (uMsg) {
case WM_PAINT:
dc = BeginPaint(hwnd, &ps);
if (dc == NULL)
abort();
drawItems(t, dc, ps.rcPaint);
EndPaint(hwnd, &ps);
return 0;
case WM_SETFONT:
t->font = (HFONT) wParam;
if (t->font == NULL)
t->font = t->defaultFont;
// also set the header font
SendMessageW(t->header, WM_SETFONT, wParam, lParam);
if (LOWORD(lParam) != FALSE) {
// the scrollbar page size will change so redraw that too
// also recalculate the header height
// TODO do that when this is FALSE too somehow
resize(t);
redrawAll(t);
}
return 0;
case WM_GETFONT:
return (LRESULT) t->font;
case WM_VSCROLL:
vscroll(t, wParam);
return 0;
case WM_MOUSEWHEEL:
wheelscroll(t, wParam);
return 0;
case WM_SIZE:
resize(t);
return 0;
case WM_LBUTTONDOWN:
selectItem(t, wParam, lParam);
return 0;
case WM_SETFOCUS:
case WM_KILLFOCUS:
// all we need to do here is redraw the highlight
// TODO localize to just the selected item
// TODO ensure giving focus works right
redrawAll(t);
return 0;
case WM_KEYDOWN:
keySelect(t, wParam, lParam);
return 0;
// TODO header double-click
case WM_NOTIFY:
if (nmhdr->hwndFrom == t->header)
switch (nmhdr->code) {
// I could use HDN_TRACK but wine doesn't emit that
case HDN_ITEMCHANGING:
case HDN_ITEMCHANGED: // TODO needed?
recomputeHScroll(t);
redrawAll(t);
return FALSE;
}
// otherwise fall through
default:
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
abort();
return 0; // unreached
}
void makeTableWindowClass(void)
{
WNDCLASSW wc;
ZeroMemory(&wc, sizeof (WNDCLASSW));
wc.lpszClassName = tableWindowClass;
wc.lpfnWndProc = tableWndProc;
wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
wc.hIcon = LoadIconW(NULL, IDI_APPLICATION);
wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); // TODO correct?
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.hInstance = GetModuleHandle(NULL);
if (RegisterClassW(&wc) == 0)
abort();
}
int main(void)
{
HWND mainwin;
MSG msg;
INITCOMMONCONTROLSEX icc;
ZeroMemory(&icc, sizeof (INITCOMMONCONTROLSEX));
icc.dwSize = sizeof (INITCOMMONCONTROLSEX);
icc.dwICC = ICC_LISTVIEW_CLASSES;
if (InitCommonControlsEx(&icc) == 0)
abort();
makeTableWindowClass();
mainwin = CreateWindowExW(0,
tableWindowClass, L"Main Window",
WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL,
CW_USEDEFAULT, CW_USEDEFAULT,
400, 400,
NULL, NULL, GetModuleHandle(NULL), NULL);
if (mainwin == NULL)
abort();
ShowWindow(mainwin, SW_SHOWDEFAULT);
if (UpdateWindow(mainwin) == 0)
abort();
while (GetMessageW(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return 0;
}
t->firstVisible is the first visible row; t->pagesize is the number of rows per vscroll page, and t->headerHeight is the height of the header control in pixels. t->wheelcarry is the mouse wheel carryover, from this.
The actual height of a row is calculated by the rowHeight() function, which vscrollto(), the routine that actually calls ScrolLWindow(), multiplies the new t->firstVisible by to figure out how many pixels to scroll.
The realClientRect() logic in vscrollto() is to make sure that only the content area gets scrolled, and not the header control.
For drawing, I change the window origin to make (0, 0) be the first item (row 0) no matter what and then I change the viewport origin to account for the header. Readers of MSDN will note that this sounds strange (the documentation for both SetWindowOrgEx() and SetViewportOrgEx() say you generally don't use both), but my attempts at accounting for the header height manually have proven disastrous.
Again, this happens on both real Windows (did this earlier today on Windows 7) and wine.
What did I do wrong? Thanks.
I've had a play around with your code and I think the problem is definitely caused by your modifying the viewport and window origins. The issue is that adjusting the origins like that changes where new drawing will appear in the window, but it doesn't cause the update region to be shifted as well.
Therefore when there's only a partially invalidated area, as you get when scrolling, some of your drawing is clipped out by the update region.
It's actually not specific to scrolling - you can also see the same effect by dragging your window off the bottom of the screen, and then slowly dragging it back into view. The window will end up completely blank. If you comment out your call to SetViewportOrgEx the problem goes away completely.
You could probably solve this by adjusting the clipping region as well - you'd have to get the current update region, shift it by the same offset, and reselect it into the DC. Alternatively, you could redesign your painting code to take the height of the header into account when painting rather than shifting the viewport offset. You mentioned you had other issues when doing this - I suspect it will be easier to solve those than you think (i.e. it seems like a bit of an XY problem).

Why is my client rectangle drawing behaving bizarrely (pictures provided) if I try to inset the client rectangle in my WM_NCCALCSIZE?

I'm trying to implement an equivalent to Cocoa's NSPopover/GTK+'s GtkPopover but on Windows using the raw Windows API. So far, I have most things working right, but I can't get the client rectangle to work... in any sensible fashion.
If I comment out my WM_PAINT handler and my WM_NCCALCSIZE below, here's what happens:
Now, if I enable WM_NCCALCSIZE, a good chunk of that red border goes away:
And if I enable my WM_PAINT, this happens. Notice that the part in the above that's black but supposed to be red stays black, but the part that's red is now COLOR_ACTIVECAPTION.
Images are from wine.
Windows XP is even worse: the GetDCEx() call (which is straight out of MSDN) fails with no last error code set, and changing it to use the seemingly equivalent GetWindowDC() results in a transparent correct red border, a transparent correct (!) red border, and the whole window having the titlebar color, respectively. wine output doesn't change.
Am I misunderstanding something about WM_NCCALCSIZE? I know all inputs and outputs are in the same coordinate space, so I assumed I could just mainpulate those coordinates and call it a day. I did try handling the valid rectangles fields (rgrc[1]/rgrc[2]), both by setting them to empty rectangles and by making rgrc[1] set to the new client rect, but neither fixed the issue here.
The MoveWindow() also doesn't seem to be it; if I remove that and keep the popover at its initial size, it still draws as above, with the same corrupt red border problem.
Thanks.
Here is the code. Because it is a test to figure out what to do, there's no error checking yet. The final code will have full error checking.
// 9 october 2014
#define UNICODE
#define _UNICODE
#define STRICT
#define STRICT_TYPED_ITEMIDS
// get Windows version right; right now Windows XP
#define WINVER 0x0501
#define _WIN32_WINNT 0x0501
#define _WIN32_WINDOWS 0x0501 /* according to Microsoft's winperf.h */
#define _WIN32_IE 0x0600 /* according to Microsoft's sdkddkver.h */
#define NTDDI_VERSION 0x05010000 /* according to Microsoft's sdkddkver.h */
#include <windows.h>
#include <commctrl.h>
#include <stdint.h>
#include <uxtheme.h>
#include <string.h>
#include <wchar.h>
#include <windowsx.h>
#include <vsstyle.h>
#include <vssym32.h>
// #qo LIBS: user32 kernel32 gdi32
// TODO
// - investigate visual styles
// - put the client and non-client areas in the right place
// - make sure redrawing is correct (especially for backgrounds)
// - wine: BLACK_PEN draws a white line? (might change later so eh)
// - should the parent window appear deactivated?
HWND popover;
#define ARROWHEIGHT 8
#define ARROWWIDTH 8 /* should be the same for smooth lines */
LRESULT CALLBACK popoverproc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC dc;
HRGN region;
POINT pt;
RECT r;
LONG width;
LONG height;
switch (uMsg) {
case WM_NCPAINT:
GetWindowRect(hwnd, &r);
width = r.right - r.left;
height = r.bottom - r.top;
dc = GetDCEx(hwnd, (HRGN) wParam, DCX_WINDOW | DCX_INTERSECTRGN);
if (dc == NULL) abort();
BeginPath(dc);
r.left = 0; r.top = 0; // everything's in device coordinates
pt.x = r.left;
pt.y = r.top + ARROWHEIGHT;
if (MoveToEx(dc, pt.x, pt.y, NULL) == 0) abort();
pt.y += height - ARROWHEIGHT;
if (LineTo(dc, pt.x, pt.y) == 0) abort();
pt.x += width;
LineTo(dc, pt.x, pt.y);
pt.y -= height - ARROWHEIGHT;
LineTo(dc, pt.x, pt.y);
pt.x -= (width / 2) - ARROWWIDTH;
LineTo(dc, pt.x, pt.y);
pt.x -= ARROWWIDTH;
pt.y -= ARROWHEIGHT;
LineTo(dc, pt.x, pt.y);
pt.x -= ARROWWIDTH;
pt.y += ARROWHEIGHT;
LineTo(dc, pt.x, pt.y);
pt.x = 0;
LineTo(dc, pt.x, pt.y);
EndPath(dc);
SetDCBrushColor(dc, RGB(255, 0, 0));
region = PathToRegion(dc);
FrameRgn(dc, region, GetStockObject(DC_BRUSH), 1, 1);
SetWindowRgn(hwnd, region, TRUE);
ReleaseDC(hwnd, dc);
return 0;
case WM_NCCALCSIZE:
{
RECT *r = (RECT *) lParam;
NCCALCSIZE_PARAMS *np = (NCCALCSIZE_PARAMS *) lParam;
if (wParam != FALSE)
r = &np->rgrc[0];
printf("%d | %d %d %d %d\n", wParam, r->left, r->top, r->right, r->bottom);
r->left++;
r->top++;
r->right--;
r->bottom--;
r->top += ARROWHEIGHT;
return 0;
}
case WM_ERASEBKGND:
return (LRESULT) GetStockObject(HOLLOW_BRUSH);
case WM_PAINT:
dc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &r);
FillRect(dc, &r, GetSysColorBrush(COLOR_ACTIVECAPTION));
EndPaint(hwnd, &ps);
return 0;
}
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
LRESULT CALLBACK wndproc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg) {
case WM_COMMAND:
if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == 100) {
MoveWindow(popover, 50, 50, 200, 200, TRUE);
ShowWindow(popover, SW_SHOW);
UpdateWindow(popover);
return 0;
}
break;
case WM_CLOSE:
PostQuitMessage(0);
return 0;
}
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
int main(int argc, char *argv[])
{
WNDCLASSW wc;
HWND mainwin, button;
MSG msg;
ZeroMemory(&wc, sizeof (WNDCLASSW));
wc.lpszClassName = L"popover";
wc.lpfnWndProc = popoverproc;
wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
wc.style = CS_DROPSHADOW | CS_NOCLOSE;
if (RegisterClassW(&wc) == 0)
abort();
popover = CreateWindowExW(WS_EX_TOPMOST,
L"popover", L"",
WS_POPUP,
0, 0, 150, 100,
NULL, NULL, NULL, NULL);
if (popover == NULL)
abort();
ZeroMemory(&wc, sizeof (WNDCLASSW));
wc.lpszClassName = L"mainwin";
wc.lpfnWndProc = wndproc;
wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
if (RegisterClassW(&wc) == 0)
abort();
mainwin = CreateWindowExW(0,
L"mainwin", L"Main Window",
WS_OVERLAPPEDWINDOW,
0, 0, 150, 100,
NULL, NULL, NULL, NULL);
if (mainwin == NULL)
abort();
button = CreateWindowExW(0,
L"button", L"Click Me",
BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE,
20, 20, 100, 40,
mainwin, (HMENU) 100, NULL, NULL);
if (button == NULL)
abort();
ShowWindow(mainwin, SW_SHOWDEFAULT);
if (UpdateWindow(mainwin) == 0)
abort();
while (GetMessageW(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return 0;
}

Resources