When I resize my window and then use the scollbar, the text gets clipped. When I resize the window again, the clipped text shows properly again.
Why does this happen, and how can I prevent it?
Screenshot:
http://i.imgur.com/CLHgowx.png
main.cpp:
#include <Windows.h>
#include "sysmets.h"
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT("Scratch");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if(!RegisterClass(&wndclass))
{
MessageBox(NULL, TEXT("Program requires Windows NT!"), szAppName, MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(szAppName, TEXT("Scratch"),
WS_OVERLAPPEDWINDOW | WS_VSCROLL,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
TEXTMETRIC tm;
PAINTSTRUCT ps;
SCROLLINFO si;
static int cxChar, cyChar, cxClient, cyClient, cxCaps;
int i, y, iPaintBeg, iPaintEnd, iVertPos;
TCHAR buffer[10];
switch(message)
{
case WM_CREATE:
hdc = GetDC(hwnd);
GetTextMetrics(hdc, &tm);
cxChar = tm.tmAveCharWidth;
cyChar = tm.tmHeight + tm.tmExternalLeading;
cxCaps = (tm.tmPitchAndFamily & 1 ? 3 : 2) * cxChar / 2;
ReleaseDC(hwnd, hdc);
return 0;
case WM_SIZE:
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
si.cbSize = sizeof(SCROLLINFO);
si.fMask = SIF_PAGE | SIF_RANGE;
si.nMin = 0;
si.nMax = NUMLINES - 1;
si.nPage = cyClient / cyChar;
SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
return 0;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
si.cbSize = sizeof(SCROLLINFO);
si.fMask = SIF_POS;
GetScrollInfo(hwnd, SB_VERT, &si);
iVertPos = si.nPos;
iPaintBeg = max(0, iVertPos + ps.rcPaint.top / cyChar);
iPaintEnd = min(NUMLINES - 1, iVertPos + ps.rcPaint.bottom / cyChar);
for (i = iPaintBeg; i < iPaintEnd; i++)
{
y = cyChar * (i - iVertPos);
TextOut(hdc, 0, y, sysmetrics[i].szLabel, lstrlen(sysmetrics[i].szLabel));
TextOut(hdc, 22 * cxCaps, y, sysmetrics[i].szDesc, lstrlen(sysmetrics[i].szDesc));
SetTextAlign(hdc, TA_TOP | TA_RIGHT);
TextOut(hdc, 60 * cxCaps, y, buffer, wsprintf(buffer, TEXT("%5d") ,GetSystemMetrics(sysmetrics[i].iIndex)));
SetTextAlign(hdc, TA_TOP | TA_LEFT);
}
EndPaint(hwnd, &ps);
return 0;
case WM_VSCROLL:
si.cbSize = sizeof(SCROLLINFO);
si.fMask = SIF_ALL;
GetScrollInfo(hwnd, SB_VERT, &si);
iVertPos = si.nPos;
switch (LOWORD(wParam))
{
case SB_LINEUP:
si.nPos -= 1;
break;
case SB_LINEDOWN:
si.nPos += 1;
break;
case SB_PAGEUP:
si.nPos -= si.nPage;
break;
case SB_PAGEDOWN:
si.nPos += si.nPage;
break;
case SB_THUMBTRACK:
si.nPos = si.nTrackPos;
break;
default:
break;
}
SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
GetScrollInfo(hwnd, SB_VERT, &si);
if(iVertPos != si.nPos)
{
ScrollWindow(hwnd, 0, cyChar * (iVertPos - si.nPos), NULL, NULL);
}
UpdateWindow(hwnd);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
sysmets.h (defines NUMLINES and sysmetrics struct)
#ifndef SYSMETS_H_
#define SYSMETS_H_
#include <windows.h>
#define NUMLINES ((int) sizeof(sysmetrics) / sizeof(sysmetrics[0]))
struct
{
int iIndex;
TCHAR *szLabel;
TCHAR *szDesc;
}
sysmetrics [] =
{
SM_CXSCREEN, TEXT("SM_CXSCREEN"), TEXT("Screen Width in pixels."),
SM_CYSCREEN, TEXT("SM_CYSCREEN"), TEXT("Screen Height in pixels."),
SM_CXVSCROLL, TEXT("SM_CXVSCROLL"), TEXT("Vertical Scroll Width"),
SM_CYHSCROLL, TEXT("SM_CYHSCROLL"), TEXT("Horizontal Scroll Height"),
SM_CYCAPTION, TEXT("SM_CYCAPTION"), TEXT("Caption Bar Height"),
SM_CXBORDER, TEXT("SM_CXBORDER"), TEXT("Window Border Width"),
SM_CYBORDER, TEXT("SM_CYBORDER"), TEXT("Window Border Height"),
SM_CXFIXEDFRAME, TEXT("SM_CXFIXEDFRAME"), TEXT("Dialog Window Frame Width"),
SM_CYFIXEDFRAME, TEXT("SM_CYFIXEDFRAME"), TEXT("Dialog Window Frame Height"),
SM_CYVTHUMB, TEXT("SM_CYVTHUMB"), TEXT("Vertical scroll thumb height"),
SM_CXHTHUMB, TEXT("SM_CXHTHUMB"), TEXT("Horizontal scroll thumb width"),
SM_CXICON, TEXT("SM_CXICON"), TEXT("Icon width"),
SM_CYICON, TEXT("SM_CYICON"), TEXT("Icon height"),
SM_CXCURSOR, TEXT("SM_CXCURSOR"), TEXT("Cursor width"),
SM_CYCURSOR, TEXT("SM_CYCURSOR"),TEXT("Cursor height"),
SM_CYMENU, TEXT("SM_CYMENU"), TEXT("Menu bar height"),
SM_CXFULLSCREEN, TEXT("SM_CXFULLSCREEN"), TEXT("Full screen client area width"),
SM_CYFULLSCREEN, TEXT("SM_CYFULLSCREEN"), TEXT("Full screen client area height"),
SM_CYKANJIWINDOW, TEXT("SM_CYKANJIWINDOW"), TEXT("Kanji window height"),
SM_MOUSEPRESENT, TEXT("SM_MOUSEPRESENT"), TEXT("Mouse present flag"),
SM_CYVSCROLL, TEXT("SM_CYVSCROLL"), TEXT("Vertical scroll arrow height"),
SM_CXHSCROLL, TEXT("SM_CXHSCROLL"), TEXT("Horizontal scroll arrow width"),
SM_DEBUG, TEXT("SM_DEBUG"), TEXT("Debug version flag"),
SM_SWAPBUTTON, TEXT("SM_SWAPBUTTON"), TEXT("Mouse buttons swapped flag"),
SM_CXMIN, TEXT("SM_CXMIN"), TEXT("Minimum window width"),
SM_CYMIN, TEXT("SM_CYMIN"), TEXT("Minimum window height"),
SM_CXSIZE, TEXT("SM_CXSIZE"), TEXT("Min/Max/Close button width"),
SM_CYSIZE, TEXT("SM_CYSIZE"), TEXT("Min/Max/Close button height"),
SM_CXSIZEFRAME, TEXT("SM_CXSIZEFRAME"), TEXT("Window sizing frame width"),
SM_CYSIZEFRAME, TEXT("SM_CYSIZEFRAME"), TEXT("Window sizing frame height"),
SM_CXMINTRACK, TEXT("SM_CXMINTRACK"), TEXT("Minimum window tracking width"),
SM_CYMINTRACK, TEXT("SM_CYMINTRACK"), TEXT("Minimum window tracking height"),
SM_CXDOUBLECLK, TEXT("SM_CXDOUBLECLK"), TEXT("Double click x tolerance"),
SM_CYDOUBLECLK, TEXT("SM_CYDOUBLECLK"), TEXT("Double click y tolerance"),
SM_CXICONSPACING, TEXT("SM_CXICONSPACING"), TEXT("Horizontal icon spacing"),
SM_CYICONSPACING, TEXT("SM_CYICONSPACING"), TEXT("Vertical icon spacing"),
SM_MENUDROPALIGNMENT, TEXT("SM_MENUDROPALIGNMENT"), TEXT("Left or right menu drop"),
SM_PENWINDOWS, TEXT("SM_PENWINDOWS"), TEXT("Pen extensions installed"),
SM_DBCSENABLED, TEXT("SM_DBCSENABLED"), TEXT("Double-Byte Char Set enabled"),
SM_CMOUSEBUTTONS, TEXT("SM_CMOUSEBUTTONS"), TEXT("Number of mouse buttons"),
SM_SECURE, TEXT("SM_SECURE"), TEXT("Security present flag"),
SM_CXEDGE, TEXT("SM_CXEDGE"), TEXT("3-D border width"),
SM_CYEDGE, TEXT("SM_CYEDGE"), TEXT("3-D border height"),
SM_CXMINSPACING, TEXT("SM_CXMINSPACING"), TEXT("Minimized window spacing width"),
SM_CYMINSPACING, TEXT("SM_CYMINSPACING"), TEXT("Minimized window spacing height"),
SM_CXSMICON, TEXT("SM_CXSMICON"), TEXT("Small icon width"),
SM_CYSMICON, TEXT("SM_CYSMICON"), TEXT("Small icon height"),
SM_CYSMCAPTION, TEXT("SM_CYSMCAPTION"), TEXT("Small caption height"),
SM_CXSMSIZE, TEXT("SM_CXSMSIZE"), TEXT("Small caption button width"),
SM_CYSMSIZE, TEXT("SM_CYSMSIZE"), TEXT("Small caption button height"),
SM_CXMENUSIZE, TEXT("SM_CXMENUSIZE"), TEXT("Menu bar button width"),
SM_CYMENUSIZE, TEXT("SM_CYMENUSIZE"), TEXT("Menu bar button height"),
SM_ARRANGE, TEXT("SM_ARRANGE"), TEXT("How minimized windows arranged"),
SM_CXMINIMIZED, TEXT("SM_CXMINIMIZED"), TEXT("Minimized window width"),
SM_CYMINIMIZED, TEXT("SM_CYMINIMIZED"), TEXT("Minimized window height"),
SM_CXMAXTRACK, TEXT("SM_CXMAXTRACK"), TEXT("Maximum draggable width"),
SM_CYMAXTRACK, TEXT("SM_CYMAXTRACK"), TEXT("Maximum draggable height"),
SM_CXMAXIMIZED, TEXT("SM_CXMAXIMIZED"), TEXT("Width of maximized window"),
SM_CYMAXIMIZED, TEXT("SM_CYMAXIMIZED"), TEXT("Height of maximized window"),
SM_NETWORK, TEXT("SM_NETWORK"), TEXT("Network present flag"),
SM_CLEANBOOT, TEXT("SM_CLEANBOOT"), TEXT("How system was booted"),
SM_CXDRAG, TEXT("SM_CXDRAG"), TEXT("Avoid drag x tolerance"),
SM_CYDRAG, TEXT("SM CYDRAG"), TEXT("Avoid drag y tolerance"),
SM_SHOWSOUNDS, TEXT("SM_SHOWSOUNDS"), TEXT("Present sounds visually"),
SM_CXMENUCHECK, TEXT("SM_CXMENUCHECK"), TEXT("Menu check-mark width"),
SM_CYMENUCHECK, TEXT("SM_CYMENUCHECK"), TEXT("Menu check-mark height"),
SM_SLOWMACHINE, TEXT("SM_SLOWMACHINE"), TEXT("Slow processor flag"),
SM_MIDEASTENABLED, TEXT("SM_MIDEASTENABLED"), TEXT("Hebrew and Arabic enabled flag"),
SM_MOUSEWHEELPRESENT, TEXT("SM_MOUSEWHEELPRESENT"), TEXT("Mouse wheel present flag"),
SM_XVIRTUALSCREEN, TEXT("SM_XVIRTUALSCREEN"), TEXT("Virtual screen x origin"),
SM_YVIRTUALSCREEN, TEXT("SM_YVIRTUALSCREEN"), TEXT("Virtual screen y origin"),
SM_CXVIRTUALSCREEN, TEXT("SM_CXVIRTUALSCREEN"), TEXT("Virtual screen width"),
SM_CYVIRTUALSCREEN, TEXT("SM_CYVIRTUALSCREEN"), TEXT("Virtual screen height"),
SM_CMONITORS, TEXT("SM_CMONITORS"), TEXT("Number of monitors"),
SM_SAMEDISPLAYFORMAT, TEXT("SM_SAMEDISPLAYFORMAT"), TEXT("Same color format flag")
};
#endif
MSDN about UpdateWindow:
The function sends a WM_PAINT message directly to the window procedure
of the specified window, bypassing the application queue. If the
update region is empty, no message is sent.
To force an update you can manually set the update region with
InvalidateRect(hwnd, NULL, TRUE)
This adds a WM_PAINT message to the message queue of hwnd. If you want to force an instant repaint you can call UpdateWindow right afterwards but that shouldn't be necessary.
Related
When I add a menubar to a window, the window didn't resize accordingly because the top portion is hidden by the menubar. I want to resize the window while taking account of menubar's height. This is what I tried.
/* g++ test.cpp -o test -Wl,-subsystem,windows */
#include <Windows.h>
#define ID_OPEN 0
#define ID_EXIT 1
#define ID_ABOUT 2
const int width = 500;
const int height = 400;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
static TCHAR szWndClassName[] = TEXT("hellowin");
HWND hWnd;
MSG msg;
WNDCLASS wndclass;
//Step 1: Registering the Window Class
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH) COLOR_BACKGROUND;
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szWndClassName;
if (!RegisterClass(&wndclass))
{
MessageBox(NULL, TEXT("This program only works in Windows NT or greater!"), TEXT("Hey dude!"), MB_OK | MB_ICONERROR);
return 1;
}
// Step 2: Creating the Window
hWnd = CreateWindow(szWndClassName, /* window class name */
TEXT("Hey!"), /* window title (or caption) */
WS_OVERLAPPEDWINDOW, /* window style */
CW_USEDEFAULT, /* initial x position */
CW_USEDEFAULT, /* initial y position */
width, /* initial window width */
height, /* initial window height */
NULL, /* parent window handle */
NULL, /* window menu handle */
hInstance, /* program instance handle */
NULL); /* creation parameters */
if (hWnd == NULL)
{
MessageBox(NULL, TEXT("Window Creation Failed!"), TEXT("Error!"),
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hWnd, iCmdShow);
UpdateWindow(hWnd);
// Step 3: The Message Loop (heart)
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
// Step 4: the Window Procedure (brain)
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
{
HMENU hMenuBar = CreateMenu();
HMENU hFile = CreatePopupMenu();
HMENU hHelp = CreatePopupMenu();
AppendMenu(hMenuBar, MF_POPUP, (UINT_PTR) hFile, "File");
AppendMenu(hMenuBar, MF_POPUP, (UINT_PTR) hHelp, "Help");
AppendMenu(hFile, MF_STRING, ID_OPEN, "Open");
AppendMenu(hFile, MF_STRING, ID_EXIT, "Exit");
AppendMenu(hHelp, MF_STRING, ID_ABOUT, "About");
SetMenu(hWnd, hMenuBar);
PMENUBARINFO pmbi;
GetMenuBarInfo(hWnd, OBJID_MENU, 0, pmbi);
RECT menuRect;
RECT windRect;
GetWindowRect(pmbi->hwndMenu, &menuRect);
GetWindowRect(hWnd, &windRect);
int width = menuRect.right - menuRect.left;
int height = (menuRect.bottom - menuRect.top) + (windRect.bottom - windRect.top);
SetWindowPos(hWnd,
0,
0,
0,
width,
height,
SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER);
break;
}
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
RECT rect;
GetClientRect(hWnd, &rect);
DrawText(hdc, TEXT("Hello World!"), -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint(hWnd, &ps);
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
I tried to retrieve rectangles of both menubar and the window and calculate the new dimension like this
int width = menuRect.right - menuRect.left;
int height = (menuRect.bottom - menuRect.top) + (windRect.bottom - windRect.top);
Unfortunately the code crashes. I have no idea which part I did wrong. Any ideas?
pmbi is an uninitialised pointer variable. Passing it to GetMenuBarInfo is therefore the likely cause of your crash. If that doesn't crash, then attempting to access pmbi->hwndMenu probably will.
Instead, you want:
MENUBARINFO mbi;
mbi.cbSize = sizeof (mbi); // see documentation
GetMenuBarInfo(hWnd, OBJID_MENU, 0, &mbi);
...
which tells GetMenuBarInfo to fill in the (stack-based) variable mbi.
Then replace pmbi->hwndMenu with mbi.hwndMenu and that should fix your problem.
I want to scroll a painted region. I use the CS_OWNDC style with WS_HSCROLL | WS_VSCROLL.My WM_PAINT block draws a line outgoing from the visible region (I suspect that I need to increase the buffer somehow).How can I make this?Please give me an example
PS. Block of code WM_HSCROLL incorrect working i don't know how to fix this.
My code:
// C++ WINAPI LEARN
#include <Windows.h>
WNDCLASS windowClass;
HDC hdc;
PAINTSTRUCT ps;
int hScroll, vScroll;
bool first = true;
LRESULT CALLBACK WndProc(HWND hWindow, UINT typeMessage, WPARAM wParam, LPARAM lParam)
{
switch (typeMessage)
{
case WM_PAINT:
hdc = BeginPaint(hWindow, &ps);
//HERE ANYTHING DRAW CODE (words, line any figure)
//(draw line out visible region)
if (first == true)
{
first = false;
MoveToEx(hdc, 5, 5, NULL);
LineTo(hdc, 900, 500);
}
EndPaint(hWindow, &ps);
break;
case WM_HSCROLL:
//SCOLLBAR NOT JOB!
if (LOWORD(wParam) == SB_LINERIGHT) // this block not job!!!
{
hScroll++;
}
else if (LOWORD(wParam) == SB_LINELEFT) // this block not job!!!
{
hScroll--;
}
else if (LOWORD(wParam) == SB_THUMBTRACK)
{
hScroll=HIWORD(wParam);
}
SetScrollPos(hWindow, SB_HORZ, hScroll, FALSE);
ScrollWindow(hWindow, hScroll, vScroll, NULL, NULL);
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
break;
}
return DefWindowProc(hWindow, typeMessage, wParam, lParam);
}
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstanse, LPSTR LpszCmdParam, int nCmdShow)
{
//CREATE WINDOW
windowClass = { 0 };
windowClass.lpszClassName = "ScrollTest";
windowClass.hInstance = hInstance;
windowClass.lpfnWndProc = WndProc;
windowClass.style = CS_OWNDC;
//REGISTER CLASS
RegisterClass(&windowClass);
HWND myWindow = ::CreateWindowEx(
0,
"ScrollTest",
"Scroll Paint",
WS_VISIBLE | WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL,
100, 100,
500, 500,
NULL,
0,
hInstance,
0
);
//TRANSLATE MESSAGE
for (MSG windowMessage; GetMessage(&windowMessage, NULL, 0, 0);)
{
DispatchMessage(&windowMessage); //TRANSLATE MESSAGES
TranslateMessage(&windowMessage); //TRANSLATE KEYS
}
}
Based on the demo, I modified part of the code and it works normally.
Some code:
LRESULT CALLBACK MyTextWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
TEXTMETRIC tm;
SCROLLINFO si;
// These variables are required to display text.
static int xChar; // horizontal scrolling unit
static int yChar; // vertical scrolling unit
static int xPos; // current horizontal scrolling position
static int yPos; // current vertical scrolling position
int x, y; // horizontal and vertical coordinates
// Create an array of lines to display.
switch (uMsg)
{
case WM_CREATE:
// Get the handle to the client area's device context.
hdc = GetDC(hwnd);
// Extract font dimensions from the text metrics.
GetTextMetrics(hdc, &tm);
xChar = tm.tmAveCharWidth;
yChar = tm.tmHeight + tm.tmExternalLeading;
// Free the device context.
ReleaseDC(hwnd, hdc);
return 0;
case WM_HSCROLL:
// Get all the vertial scroll bar information.
si.cbSize = sizeof(si);
si.fMask = SIF_ALL;
// Save the position for comparison later on.
GetScrollInfo(hwnd, SB_HORZ, &si);
xPos = si.nPos;
switch (LOWORD(wParam))
{
// User clicked the left arrow.
case SB_LINELEFT:
si.nPos -= 1;
break;
// User clicked the right arrow.
case SB_LINERIGHT:
si.nPos += 1;
break;
// User clicked the scroll bar shaft left of the scroll box.
case SB_PAGELEFT:
si.nPos -= si.nPage;
break;
// User clicked the scroll bar shaft right of the scroll box.
case SB_PAGERIGHT:
si.nPos += si.nPage;
break;
// User dragged the scroll box.
case SB_THUMBTRACK:
si.nPos = si.nTrackPos;
break;
default:
break;
}
// Set the position and then retrieve it. Due to adjustments
// by Windows it may not be the same as the value set.
si.fMask = SIF_POS;
SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);
GetScrollInfo(hwnd, SB_HORZ, &si);
// If the position has changed, scroll the window.
if (si.nPos != xPos)
{
ScrollWindow(hwnd, xChar * (xPos - si.nPos), 0, NULL, NULL);
}
return 0;
case WM_VSCROLL:
// Get all the vertial scroll bar information.
si.cbSize = sizeof(si);
si.fMask = SIF_ALL;
GetScrollInfo(hwnd, SB_VERT, &si);
// Save the position for comparison later on.
yPos = si.nPos;
switch (LOWORD(wParam))
{
// User clicked the HOME keyboard key.
case SB_TOP:
si.nPos = si.nMin;
break;
// User clicked the END keyboard key.
case SB_BOTTOM:
si.nPos = si.nMax;
break;
// User clicked the top arrow.
case SB_LINEUP:
si.nPos -= 1;
break;
// User clicked the bottom arrow.
case SB_LINEDOWN:
si.nPos += 1;
break;
// User clicked the scroll bar shaft above the scroll box.
case SB_PAGEUP:
si.nPos -= si.nPage;
break;
// User clicked the scroll bar shaft below the scroll box.
case SB_PAGEDOWN:
si.nPos += si.nPage;
break;
// User dragged the scroll box.
case SB_THUMBTRACK:
si.nPos = si.nTrackPos;
break;
default:
break;
}
// Set the position and then retrieve it. Due to adjustments
// by Windows it may not be the same as the value set.
si.fMask = SIF_POS;
SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
GetScrollInfo(hwnd, SB_VERT, &si);
// If the position has changed, scroll window and update it.
if (si.nPos != yPos)
{
ScrollWindow(hwnd, 0, yChar * (yPos - si.nPos), NULL, NULL);
UpdateWindow(hwnd);
}
return 0;
case WM_PAINT:
// Prepare the window for painting.
hdc = BeginPaint(hwnd, &ps);
// Get vertical scroll bar position.
si.cbSize = sizeof(si);
si.fMask = SIF_POS;
GetScrollInfo(hwnd, SB_VERT, &si);
yPos = si.nPos;
// Get horizontal scroll bar position.
GetScrollInfo(hwnd, SB_HORZ, &si);
xPos = si.nPos;
x = xChar * (1 - xPos);
y = yChar * (1 - yPos);
MoveToEx(hdc, 5 + x, 5 + y, NULL);
LineTo(hdc, 900 + x, 500 + y);
// Indicate that painting is finished.
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
Debug:
I created a ListView using CreateWindowEx and using the WC_LISTVIEW as class name.
I'm trying to create a smooth scrolling. Everything works perfectly except that list is not drawn correctly. See below the screenshot of the list:
The list view has the following style in CreateWindowEx:
WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_NOCOLUMNHEADER |
WS_TABSTOP | WS_BORDER | LVS_SHOWSELALWAYS | LVS_SINGLESEL | LVS_OWNERDRAWFIXED
I'm using a timer to scroll window. It does the following:
ScrollWindowEx(
listHandle,
0,
step * linesDelta,
NULL,
NULL,
0, 0, 0
);
UpdateWindow(listHandle);
Scroll works perfectly except painting.
I tried:
UpdateWindow() - screenshoot attached
RedrawWindow with all possible options - window is painted only once
InvalidateRect + UpdateWindow = same as 2
InvalidateRect + SendMessage(hwnd, WM_PAINT, 0, 0) - same as 2
The code that paints the item for the list is below:
LRESULT drawItem(HWND hwnd, DRAWITEMSTRUCT* drawStruct) {
Item *itemData = (Item *)drawStruct->itemData;
HDC hdc = drawStruct->hDC;
COLORREF backgroundColor;
COLORREF oldColor;
if (drawStruct->itemState & ODS_SELECTED || ListView_GetHotItem(hwnd) == drawStruct->itemID) {
backgroundColor = GetSysColor(COLOR_HIGHLIGHT);
oldColor = SetTextColor(hdc, GetSysColor(COLOR_HIGHLIGHTTEXT));
} else {
backgroundColor = RGB(255, 255, 255);
oldColor = SetTextColor(hdc, GetSysColor(COLOR_CAPTIONTEXT));
}
HBRUSH backgroundBrush = CreateSolidBrush(backgroundColor);
HBRUSH hOldBrush = (HBRUSH)SelectObject(hdc, backgroundBrush);
FillRect(hdc, &drawStruct->rcItem, backgroundBrush);
drawStruct->rcItem.left += 5;
drawStruct->rcItem.right -= 5;
drawStruct->rcItem.left += 30;
DrawText(hdc, itemData->path, -1, &drawStruct->rcItem,
DT_NOPREFIX | DT_SINGLELINE | DT_END_ELLIPSIS);
drawStruct->rcItem.left -= 30;
if (itemData->searchData && itemData->searchData->bitmap) {
HBITMAP bitmap = itemData->searchData->bitmap;
HDC hdcMem = CreateCompatibleDC(hdc);
HGDIOBJ oldBitmap = SelectObject(hdcMem, bitmap);
BITMAPINFO bi = { 0 };
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
// Get the bitmap info header.
if (0 != GetDIBits(
hdcMem, // hdc
bitmap, // hbmp
0, // uStartScan
0, // cScanLines
NULL, // lpvBits
&bi,
DIB_RGB_COLORS
)) {
BLENDFUNCTION blendFunc;
blendFunc.BlendOp = AC_SRC_OVER;
blendFunc.BlendFlags = 0;
blendFunc.SourceConstantAlpha = 255;
blendFunc.AlphaFormat = AC_SRC_ALPHA;
AlphaBlend(hdc,
drawStruct->rcItem.left + 2, //dest X
drawStruct->rcItem.top + 3, //dest Y
bi.bmiHeader.biWidth,
bi.bmiHeader.biHeight,
hdcMem, 0, 0,
bi.bmiHeader.biWidth,
bi.bmiHeader.biHeight, blendFunc);
}
SelectObject(hdcMem, oldBitmap);
DeleteDC(hdcMem);
}
SelectObject(hdc, hOldBrush);
DeleteObject(backgroundBrush);
SetTextColor(hdc, oldColor);
return 0;
}
Does anyone know a solution for this?
Please see below a complete example created from scratch that has exactly the same behavior:
#include "stdafx.h"
#include "TestList.h"
#include <strsafe.h>
#include <commctrl.h>
#define MAX_LOADSTRING 100
#define ID_LIST_BOX 200
#define TIMER_ID_SMOOTH_SCROLL 100
class ListData {
int scrollToDelta;
int currentScrollPos;
int numPixelsToChangeScrollPos;
int numPixelsChanged;
public:
HWND listWindow;
WNDPROC defaultListProcedure;
void startSmoothScrolling(HWND hwnd, int delta) {
if (delta < 0) {
scrollToDelta = 100;
} else {
scrollToDelta = -100;
}
SCROLLINFO si;
si.cbSize = sizeof(si);
si.fMask = SIF_RANGE | SIF_POS;
if (GetScrollInfo(listWindow, SB_VERT, &si)) {
double count = SendMessage(listWindow, LVM_GETITEMCOUNT, 0, 0);
double totalHeight = count * 30;
currentScrollPos = (int)((totalHeight * (double)si.nPos) / (double)si.nMax);
numPixelsToChangeScrollPos = totalHeight / si.nMax;
numPixelsChanged = 0;
} else {
currentScrollPos = 0;
numPixelsChanged = 0;
numPixelsToChangeScrollPos = 30;
}
}
void smoothScroll(HWND listHandle) {
SCROLLINFO si;
si.cbSize = sizeof(si);
si.fMask = SIF_RANGE | SIF_POS;
DWORD linesDelta;
SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &linesDelta, 0);
if (scrollToDelta < 0) {
if (GetScrollInfo(listHandle, SB_VERT, &si)) {
if (si.nPos == 0) {
KillTimer(listHandle, TIMER_ID_SMOOTH_SCROLL);
return;
}
}
scrollToDelta += 5;
int step = -5;
if (scrollToDelta > -80) {
step = -4;
} else if (scrollToDelta > -60) {
step = -3;
} else if (scrollToDelta > -40) {
step = -3;
} else if (scrollToDelta > -20) {
step = -2;
}
numPixelsChanged += abs(step);
if (numPixelsChanged >= numPixelsToChangeScrollPos) {
int posDelta = numPixelsChanged / numPixelsToChangeScrollPos;
numPixelsChanged -= posDelta * numPixelsToChangeScrollPos;
si.nPos = si.nPos + posDelta;
si.fMask = SIF_POS;
SetScrollInfo(listHandle, SB_VERT, &si, TRUE);
}
ScrollWindowEx(
listHandle,
0,
step * linesDelta,
NULL,
NULL,
0, 0,
SW_INVALIDATE);
if (scrollToDelta >= 0) {
KillTimer(listHandle, TIMER_ID_SMOOTH_SCROLL);
}
} else {
if (GetScrollInfo(listHandle, SB_VERT, &si)) {
int pos = GetScrollPos(listHandle, SB_VERT);
if (pos == si.nMax) {
KillTimer(listHandle, TIMER_ID_SMOOTH_SCROLL);
return;
}
}
scrollToDelta -= 5;
int step = 5;
if (scrollToDelta > -80) {
step = 4;
} else if (scrollToDelta > -60) {
step = 3;
} else if (scrollToDelta > -40) {
step = 3;
} else if (scrollToDelta > -20) {
step = 2;
}
numPixelsChanged += abs(step);
if (numPixelsChanged >= numPixelsToChangeScrollPos) {
int posDelta = numPixelsChanged / numPixelsToChangeScrollPos;
numPixelsChanged -= posDelta * numPixelsToChangeScrollPos;
si.nPos = si.nPos - posDelta;
si.fMask = SIF_POS;
SetScrollInfo(listHandle, SB_VERT, &si, TRUE);
}
ScrollWindowEx(
listHandle,
0,
step * linesDelta,
NULL,
NULL,
0, 0, 0
);
if (scrollToDelta <= 0) {
KillTimer(listHandle, TIMER_ID_SMOOTH_SCROLL);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//RedrawWindow(listHandle, NULL, NULL,
// RDW_UPDATENOW | RDW_INTERNALPAINT | RDW_INVALIDATE | RDW_NOERASE | RDW_ALLCHILDREN | RDW_ERASENOW);
//InvalidateRect(listHandle, NULL, FALSE);
//SendMessage(listHandle, WM_PAINT, 0, 0);
UpdateWindow(listHandle);
//ListView_RedrawItems(listHandle, 0, 300);
////////////////////////////////////////////////////////////////////////////////////////////////////
}
};
struct Item {
WCHAR *name;
};
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
StringCchCopy(szTitle, MAX_LOADSTRING, L"Test");
StringCchCopy(szWindowClass, MAX_LOADSTRING, L"TestClassList");
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TESTLIST));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TESTLIST));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_TESTLIST);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
LRESULT drawItem(HWND hwnd, DRAWITEMSTRUCT* drawStruct) {
Item *itemData = (Item *)drawStruct->itemData;
HDC hdc = drawStruct->hDC;
COLORREF backgroundColor;
//pcd->clrTextBk;
COLORREF oldColor;
if (drawStruct->itemState & ODS_SELECTED || ListView_GetHotItem(hwnd) == drawStruct->itemID) {
backgroundColor = GetSysColor(COLOR_HIGHLIGHT);
oldColor = SetTextColor(hdc, GetSysColor(COLOR_HIGHLIGHTTEXT));
} else {
backgroundColor = RGB(255, 255, 255);
oldColor = SetTextColor(hdc, GetSysColor(COLOR_CAPTIONTEXT));
}
HBRUSH backgroundBrush = CreateSolidBrush(backgroundColor);
HBRUSH hOldBrush = (HBRUSH)SelectObject(hdc, backgroundBrush);
FillRect(hdc, &drawStruct->rcItem, backgroundBrush);
drawStruct->rcItem.left += 5;
drawStruct->rcItem.right -= 5;
drawStruct->rcItem.left += 30;
DrawText(hdc, itemData->name, -1, &drawStruct->rcItem,
DT_NOPREFIX | DT_SINGLELINE | DT_END_ELLIPSIS);
drawStruct->rcItem.left -= 30;
SelectObject(hdc, hOldBrush);
DeleteObject(backgroundBrush);
SetTextColor(hdc, oldColor);
return 0;
}
LRESULT CALLBACK ListViewWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
////////////////////////////////////////////////////////////////////////////////////////////////////
case WM_TIMER: {
if (wParam == TIMER_ID_SMOOTH_SCROLL) {
ListData *listData = (ListData*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
listData->smoothScroll(hwnd);
}
break;
}
case WM_MOUSEWHEEL: {
int delta = HIWORD(wParam);
ListData *listData = (ListData*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
listData->startSmoothScrolling(hwnd, delta);
SetTimer(hwnd, TIMER_ID_SMOOTH_SCROLL, 200, NULL);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
default:
ListData *listData = (ListData*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
return CallWindowProc(listData->defaultListProcedure, hwnd, uMsg, wParam, lParam);
}
return 0;
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
100, 100, 400, 400, nullptr, nullptr, hInstance, nullptr);
if (!hWnd) {
return FALSE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
HWND listWindow = CreateWindowEx(
0,
WC_LISTVIEW,
L"",
WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_NOCOLUMNHEADER |
WS_TABSTOP | WS_BORDER | LVS_SHOWSELALWAYS | LVS_SINGLESEL | LVS_OWNERDRAWFIXED,
1, //x
1, //y
400 - 20, //width
400 - 20, //height
hWnd,
(HMENU)ID_LIST_BOX,
hInstance,
NULL);
ListData *listData = new ListData();
listData->listWindow = listWindow;
SetWindowLongPtr(listWindow, GWLP_USERDATA, (LPARAM)listData);
listData->defaultListProcedure = (WNDPROC)SetWindowLongPtr(listWindow, GWLP_WNDPROC, (LONG_PTR)ListViewWindowProc);
ListView_SetExtendedListViewStyle(listWindow, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_AUTOSIZECOLUMNS);
SendMessage(listWindow, LVM_SETTEXTBKCOLOR, 0, 0xFFFFFF);
LVCOLUMN col;
col.mask = LVCF_TEXT | LVCF_WIDTH;
col.pszText = L"";
col.cx = 390;
SendMessage(listWindow, LVM_INSERTCOLUMN, 0, (LPARAM)&col);
LVITEM item;
item.mask = LVIF_PARAM | LVIF_TEXT;
item.iSubItem = 0;
for (int i = 0; i < 300; i++) {
item.iItem = i;
Item *itemData = (Item*)malloc(sizeof(Item));
WCHAR *name = (WCHAR*)malloc(sizeof(WCHAR) * 30);;
wsprintf(name, L"Item Name %d", i);
itemData->name = name;
item.pszText = name;
item.lParam = (LPARAM)itemData;
SendMessage(listWindow, LVM_INSERTITEM, 0, (LPARAM)&item);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// 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)
{
switch (message) {
case WM_DRAWITEM: {
////////////////////////////////////////////////////////////////////////////////////////////////////
if (wParam == ID_LIST_BOX) {
DRAWITEMSTRUCT *drawStruct = (DRAWITEMSTRUCT*)lParam;
drawItem(drawStruct->hwndItem, drawStruct);
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
break;
}
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_MEASUREITEM: {
if (wParam == ID_LIST_BOX) {
MEASUREITEMSTRUCT *measureStruct = (MEASUREITEMSTRUCT*)lParam;
measureStruct->itemHeight = 30;
measureStruct->itemWidth = 390;
return TRUE;
}
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
Here's an old trick: before invoking ScrollWindowEx() invalidate the entire listHandle area without erasing the background.
InvalidateRect(listHandle, NULL, FALSE);
ScrollWindowEx(...
Have a nice day!
From MSDN for ScrollWindowEx:
If the SW_INVALIDATE and SW_ERASE flags are not specified, ScrollWindowEx does not invalidate the area that is scrolled from. If either of these flags is set, ScrollWindowEx invalidates this area. The area is not updated until the application calls the UpdateWindow function, calls the RedrawWindow function (specifying the RDW_UPDATENOW or RDW_ERASENOW flag), or retrieves the WM_PAINT message from the application queue.
So let's look at what you tried:
UpdateWindow() - screenshoot attached
Nothing got invalidated, so the update region is empty, so UpdateWindow does nothing.
RedrawWindow with all possible options - window is painted only once
If called correctly, this should invalidate the client. You can cause the WM_ERASEBKGND to happen immediately, but the WM_PAINT message will come only when there's nothing else in the queue. I suspect this didn't work because the WM_TIMER takes priority over the WM_PAINT. (Both are special messages in that they are not actually posted but synthesized when you call GetMessage and nothing else is pending.)
InvalidateRect + UpdateWindow = same as 2
I would expect this to work, but it seems to make more sense to pass the flags to ScrollWindowEx to get the invalidation. I think what's happening is that the control is not designed to draw the items an non-integral positions. So you're getting invalidation, but the window is attempting to draw the items at different offsets than you expect. I don't see an straightforward way to solve this.
InvalidateRect + SendMessage(hwnd, WM_PAINT, 0, 0) - same as 2
That's not a valid WM_PAINT message. Don't do that.
The problem is that ListView is created using the LVS_REPORT flag. This means that list cannot scroll smoothly but only in lines. I.e. if line height is, for instance, 25, scrolling 20 pixels will make the list scroll 25 pixels.
One more issue is that ScrollWindowEx doesn't really scroll the list (or at least it wasn't used correctly). In order to scroll the list, the ListView_Scroll macro should be used (which again scrolls by lines not by pixels).
INTRODUCTION AND RELEVANT INFORMATION:
I am trying to paint the image in my main window in its natural size. Currently I need to render EMF.
After browsing through Internet, I found this MSDN example.
PROBLEM:
I have given it a try, and found out it doesn't work well.
After user right clicks, as instructions say, desktop screenshot is properly painted in the main window.
However, when user resizes the window, paint artifacts occur like the ones on the image below. The below effect also occurs when user scrolls a little and then resizes the window.
Here is the image:
This is my first time trying to scroll an image, and using scrollbars, so I really have a hard time figuring out a solution.
QUESTIONS:
How to fix article code to remove this visual artifact?
Can you recommend another example, like tutorial/code example/etc that
I can study?
Can you provide "verbal" instructions/guidelines that could help me?
To make your task even easier, here is the smallest code possible that reproduces the problem. Take note that I have simply copy/pasted the window procedure and added minimal code for program to create working demonstration:
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
SCROLLINFO si;
// These variables are required by BitBlt.
static HDC hdcWin; // window DC
static HDC hdcScreen; // DC for entire screen
static HDC hdcScreenCompat; // memory DC for screen
static HBITMAP hbmpCompat; // bitmap handle to old DC
static BITMAP bmp; // bitmap data structure
static BOOL fBlt; // TRUE if BitBlt occurred
static BOOL fScroll; // TRUE if scrolling occurred
static BOOL fSize; // TRUE if fBlt & WM_SIZE
// These variables are required for horizontal scrolling.
static int xMinScroll; // minimum horizontal scroll value
static int xCurrentScroll; // current horizontal scroll value
static int xMaxScroll; // maximum horizontal scroll value
// These variables are required for vertical scrolling.
static int yMinScroll; // minimum vertical scroll value
static int yCurrentScroll; // current vertical scroll value
static int yMaxScroll; // maximum vertical scroll value
switch (uMsg)
{
case WM_CREATE:
// Create a normal DC and a memory DC for the entire
// screen. The normal DC provides a snapshot of the
// screen contents. The memory DC keeps a copy of this
// snapshot in the associated bitmap.
hdcScreen = CreateDC(L"DISPLAY", (PCTSTR)NULL,
(PCTSTR)NULL, (CONST DEVMODE *) NULL);
hdcScreenCompat = CreateCompatibleDC(hdcScreen);
// Retrieve the metrics for the bitmap associated with the
// regular device context.
bmp.bmBitsPixel =
(BYTE)GetDeviceCaps(hdcScreen, BITSPIXEL);
bmp.bmPlanes = (BYTE)GetDeviceCaps(hdcScreen, PLANES);
bmp.bmWidth = GetDeviceCaps(hdcScreen, HORZRES);
bmp.bmHeight = GetDeviceCaps(hdcScreen, VERTRES);
// The width must be byte-aligned.
bmp.bmWidthBytes = ((bmp.bmWidth + 15) &~15) / 8;
// Create a bitmap for the compatible DC.
hbmpCompat = CreateBitmap(bmp.bmWidth, bmp.bmHeight,
bmp.bmPlanes, bmp.bmBitsPixel, (CONST VOID *) NULL);
// Select the bitmap for the compatible DC.
SelectObject(hdcScreenCompat, hbmpCompat);
// Initialize the flags.
fBlt = FALSE;
fScroll = FALSE;
fSize = FALSE;
// Initialize the horizontal scrolling variables.
xMinScroll = 0;
xCurrentScroll = 0;
xMaxScroll = 0;
// Initialize the vertical scrolling variables.
yMinScroll = 0;
yCurrentScroll = 0;
yMaxScroll = 0;
break;
case WM_SIZE:
{
int xNewSize;
int yNewSize;
xNewSize = LOWORD(lParam);
yNewSize = HIWORD(lParam);
if (fBlt)
fSize = TRUE;
// The horizontal scrolling range is defined by
// (bitmap_width) - (client_width). The current horizontal
// scroll value remains within the horizontal scrolling range.
xMaxScroll = max(bmp.bmWidth - xNewSize, 0);
xCurrentScroll = min(xCurrentScroll, xMaxScroll);
si.cbSize = sizeof(si);
si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
si.nMin = xMinScroll;
si.nMax = bmp.bmWidth;
si.nPage = xNewSize;
si.nPos = xCurrentScroll;
SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);
// The vertical scrolling range is defined by
// (bitmap_height) - (client_height). The current vertical
// scroll value remains within the vertical scrolling range.
yMaxScroll = max(bmp.bmHeight - yNewSize, 0);
yCurrentScroll = min(yCurrentScroll, yMaxScroll);
si.cbSize = sizeof(si);
si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
si.nMin = yMinScroll;
si.nMax = bmp.bmHeight;
si.nPage = yNewSize;
si.nPos = yCurrentScroll;
SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
break;
}
case WM_PAINT:
{
PRECT prect;
hdc = BeginPaint(hwnd, &ps);
// If the window has been resized and the user has
// captured the screen, use the following call to
// BitBlt to paint the window's client area.
if (fSize)
{
BitBlt(ps.hdc,
0, 0,
bmp.bmWidth, bmp.bmHeight,
hdcScreenCompat,
xCurrentScroll, yCurrentScroll,
SRCCOPY);
fSize = FALSE;
}
// If scrolling has occurred, use the following call to
// BitBlt to paint the invalid rectangle.
//
// The coordinates of this rectangle are specified in the
// RECT structure to which prect points.
//
// Note that it is necessary to increment the seventh
// argument (prect->left) by xCurrentScroll and the
// eighth argument (prect->top) by yCurrentScroll in
// order to map the correct pixels from the source bitmap.
if (fScroll)
{
prect = &ps.rcPaint;
BitBlt(ps.hdc,
prect->left, prect->top,
(prect->right - prect->left),
(prect->bottom - prect->top),
hdcScreenCompat,
prect->left + xCurrentScroll,
prect->top + yCurrentScroll,
SRCCOPY);
fScroll = FALSE;
}
EndPaint(hwnd, &ps);
break;
}
case WM_HSCROLL:
{
int xDelta; // xDelta = new_pos - current_pos
int xNewPos; // new position
int yDelta = 0;
switch (LOWORD(wParam))
{
// User clicked the scroll bar shaft left of the scroll box.
case SB_PAGEUP:
xNewPos = xCurrentScroll - 50;
break;
// User clicked the scroll bar shaft right of the scroll box.
case SB_PAGEDOWN:
xNewPos = xCurrentScroll + 50;
break;
// User clicked the left arrow.
case SB_LINEUP:
xNewPos = xCurrentScroll - 5;
break;
// User clicked the right arrow.
case SB_LINEDOWN:
xNewPos = xCurrentScroll + 5;
break;
// User dragged the scroll box.
case SB_THUMBPOSITION:
xNewPos = HIWORD(wParam);
break;
default:
xNewPos = xCurrentScroll;
}
// New position must be between 0 and the screen width.
xNewPos = max(0, xNewPos);
xNewPos = min(xMaxScroll, xNewPos);
// If the current position does not change, do not scroll.
if (xNewPos == xCurrentScroll)
break;
// Set the scroll flag to TRUE.
fScroll = TRUE;
// Determine the amount scrolled (in pixels).
xDelta = xNewPos - xCurrentScroll;
// Reset the current scroll position.
xCurrentScroll = xNewPos;
// Scroll the window. (The system repaints most of the
// client area when ScrollWindowEx is called; however, it is
// necessary to call UpdateWindow in order to repaint the
// rectangle of pixels that were invalidated.)
ScrollWindowEx(hwnd, -xDelta, -yDelta, (CONST RECT *) NULL,
(CONST RECT *) NULL, (HRGN)NULL, (PRECT)NULL,
SW_INVALIDATE);
UpdateWindow(hwnd);
// Reset the scroll bar.
si.cbSize = sizeof(si);
si.fMask = SIF_POS;
si.nPos = xCurrentScroll;
SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);
break;
}
case WM_VSCROLL:
{
int xDelta = 0;
int yDelta; // yDelta = new_pos - current_pos
int yNewPos; // new position
switch (LOWORD(wParam))
{
// User clicked the scroll bar shaft above the scroll box.
case SB_PAGEUP:
yNewPos = yCurrentScroll - 50;
break;
// User clicked the scroll bar shaft below the scroll box.
case SB_PAGEDOWN:
yNewPos = yCurrentScroll + 50;
break;
// User clicked the top arrow.
case SB_LINEUP:
yNewPos = yCurrentScroll - 5;
break;
// User clicked the bottom arrow.
case SB_LINEDOWN:
yNewPos = yCurrentScroll + 5;
break;
// User dragged the scroll box.
case SB_THUMBPOSITION:
yNewPos = HIWORD(wParam);
break;
default:
yNewPos = yCurrentScroll;
}
// New position must be between 0 and the screen height.
yNewPos = max(0, yNewPos);
yNewPos = min(yMaxScroll, yNewPos);
// If the current position does not change, do not scroll.
if (yNewPos == yCurrentScroll)
break;
// Set the scroll flag to TRUE.
fScroll = TRUE;
// Determine the amount scrolled (in pixels).
yDelta = yNewPos - yCurrentScroll;
// Reset the current scroll position.
yCurrentScroll = yNewPos;
// Scroll the window. (The system repaints most of the
// client area when ScrollWindowEx is called; however, it is
// necessary to call UpdateWindow in order to repaint the
// rectangle of pixels that were invalidated.)
ScrollWindowEx(hwnd, -xDelta, -yDelta, (CONST RECT *) NULL,
(CONST RECT *) NULL, (HRGN)NULL, (PRECT)NULL,
SW_INVALIDATE);
UpdateWindow(hwnd);
// Reset the scroll bar.
si.cbSize = sizeof(si);
si.fMask = SIF_POS;
si.nPos = yCurrentScroll;
SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
break;
}
case WM_RBUTTONDOWN:
{
// Get the compatible DC of the client area.
hdcWin = GetDC(hwnd);
// Fill the client area to remove any existing contents.
RECT rect;
GetClientRect(hwnd, &rect);
FillRect(hdcWin, &rect, (HBRUSH)(COLOR_WINDOW + 1));
// Copy the contents of the current screen
// into the compatible DC.
BitBlt(hdcScreenCompat, 0, 0, bmp.bmWidth,
bmp.bmHeight, hdcScreen, 0, 0, SRCCOPY);
// Copy the compatible DC to the client area.
BitBlt(hdcWin, 0, 0, bmp.bmWidth, bmp.bmHeight,
hdcScreenCompat, 0, 0, SRCCOPY);
ReleaseDC(hwnd, hdcWin);
fBlt = TRUE;
break;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
// WinMain
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine,
int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd;
MSG Msg;
// register main window class
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
wc.lpszMenuName = NULL;
wc.lpszClassName = L"Main_Window";
wc.hIconSm = LoadIcon(hInstance, IDI_APPLICATION);
if (!RegisterClassEx(&wc))
{
MessageBox(NULL, L"Window Registration Failed!", L"Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
// create main window
hwnd = CreateWindowEx(0, L"Main_Window", L"Scrollable map",
WS_OVERLAPPEDWINDOW | WS_VSCROLL | WS_HSCROLL,
50, 50, 400, 400, NULL, NULL, hInstance, 0);
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
From your description the problem seems to be simply that your window isn't being repainted when it's resized.
Either use InvalidateRect to force a repaint of the newly uncovered areas when your window is enlarged, or set the CS_VREDRAW and CS_HREDRAW styles on your window class to have the client area repainted automatically.
I'm having trouble with a WINAPI project. There are two problems, when I launch a window with the below code, the height parameter behaves strangely. It seems to cap off at 1092, 18 pixels below where I need it on my computer. The second problem is that the window has no edges nor the top menu bar, until I use the Windows+Up/Down key combination to minimize and maximize it, then it behaves normally. I'm using the below code to initialize the window (the only code that runs before this initializes the options.pxXRes and other variables used below):
//Set up the window class
WNDCLASSEX wndClass;
wndClass.cbSize = sizeof(WNDCLASSEX);
wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = &WndHandleInput;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = GetModuleHandle(nullptr);
wndClass.hIcon = nullptr;
wndClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
wndClass.lpszMenuName = nullptr;
wndClass.lpszClassName = "ToastCatClass";
wndClass.hIconSm = nullptr;
RegisterClassEx(&wndClass);
RECT wndRect;
if (options.fullscreen) {
wndRect.left = 0;
wndRect.right = options.pxXRes;
wndRect.top = 0;
wndRect.bottom = options.pxYRes;
AdjustWindowRect(&wndRect, WS_OVERLAPPEDWINDOW, false);
} else {
wndRect.left = (GetPXXRes() - options.pxXRes) / 2;
wndRect.right = options.pxXRes;
wndRect.top = (GetPXYRes() - options.pxYRes) / 2;
wndRect.bottom = options.pxYRes;
AdjustWindowRect(&wndRect, WS_OVERLAPPEDWINDOW, false);
}
hWnd = CreateWindowEx(
0,
wndClass.lpszClassName,
"ToastCat",
WS_OVERLAPPEDWINDOW,
wndRect.left,
wndRect.top,
wndRect.right - wndRect.left,
wndRect.bottom - wndRect.top,
nullptr,
nullptr,
wndClass.hInstance,
nullptr
);
assert(hWnd != nullptr, "Failure to launch window.");
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
The Window procedure is as follows:
LRESULT __stdcall WndHandleInput(HWND hWndParam, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_NCCREATE:
return true;
case WM_KEYDOWN:
switch (wParam) {
//TODO: Update controls
}
break;
case WM_KEYUP:
switch (wParam) {
//TODO: Update controls
}
break;
case WM_CLOSE:
case WM_QUIT:
Cleanup();
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
}
Windows have two different rectangles:
the client rectangle which is the area of the window to which the application can draw or create child windows within and
the window rectangle which is the outer rectangle of the window (including borders, menu, ...).
By calling AdjustWindowRect you're converting a client rectangle to a window rectangle. Therefore the borders and the menu cannot be visible if you're setting up a client rectangle as big as the entire screen, converting it to a window rectangle and creating a window with such size. If you look at wndRect after the call to AdjustWindowRect(..) using the debugger you will see that top and left are negative.
That the window height is off by some pixels is the default windows behavior. Windows by default does not allow windows to have a height bigger than the screen height because this will move the caption out of the area the mouse can get to. To change this you have to process message WM_GETMINMAXINFO:
case WM_GETMINMAXINFO:
DefWindowProc(hWnd, msg, wParam, lParam);
MINMAXINFO *pmmi = (MINMAXINFO*)lParam;
pmmi->ptMaxTrackSize.x *= 2; // just make it bigger...
pmmi->ptMaxTrackSize.y *= 2; //
return 0;
If you just want to start your window either maximized (with all controls and border visible) or at some other defined location just do the following: Create your window normally with the wndRect initialized within the else-part of if (options.fullscreen) and change the call of ShowWindow(..) as follows:
if (options.fullscreen)
{
ShowWindow(hWnd, SW_MAXIMIZE);
}
else
{
ShowWindow(hWnd, SW_SHOWDEFAULT);
}
UpdateWindow(hWnd);