change color of specific label win32 - winapi

I have a set of labels [8][8] each with it's own Id, from a routine I call to change label color giving the hWnd, but then nothing happens, but if i don't specify an Id on case WM_CTLCOLORSTATIC: all labels change color
DWORD WINAPI changecolor(LPVOID lpParameter){
clrLabelBkGnd = RGB(255, 255, 0x00);
InvalidateRect(hWndLabel[0][0], NULL, TRUE);
return 0;
}
CALL back function
case WM_CTLCOLORSTATIC:
ctrlID = GetDlgCtrlID((HWND)lParam);
if (ctrlID == 1000) {
hdc = reinterpret_cast<HDC>(wParam);
SetBkColor(hdc, clrLabelBkGnd);
return reinterpret_cast<LRESULT>(hBrushLabel);
}
else break;
main program
/* fill the labels IDs*/
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
labelId[i][j] = (i * 8 + j)+1000;
}
}
In this example when I specify id 1000 which exist hWndLabel[0][0] nothing is colored, but if I don't specify id or if i put id > 1000 in case WM_CTLCOLORSTATIC: all labels are colored even by calling only hWndLabel[0][0]

This part is wrong:
case WM_CTLCOLORSTATIC:
if (LOWORD(wParam) == 1000) {
hdc = reinterpret_cast<HDC>(wParam);
Since wParam is the handle to the device context, why are you using it's low word as the ID of the control?
Take a look at WM_CTLCOLORSTATIC:
wParam
Handle to the device context for the static control window.
lParam
Handle to the static control.
What you need to use is lParam.
DWORD ctrlID = GetDlgCtrlID((HWND)lParam));
if (ctrlID == 1000)
{
}
UPDATE: Based on the comments you provided, you need to have a mechanism to retain the ID of the label that has been invalidated.
DWORD WINAPI changecolor(LPVOID lpParameter)
{
clrLabelBkGnd = RGB(255, 255, 0x00);
someVariableToHoldLabelIdWithRightScope = labelId[0][0]; // Or GetDlgCtrlID(hWndLabel[0][0]);
InvalidateRect(hWndLabel[0][0], NULL, TRUE);
return 0;
}
Then, when you handle the color:
case WM_CTLCOLORSTATIC:
ctrlID = GetDlgCtrlID((HWND)lParam);
if (ctrlID == someVariableToHoldLabelIdWithRightScope)
{
hdc = reinterpret_cast<HDC>(wParam);
SetBkColor(hdc, clrLabelBkGnd);
return reinterpret_cast<LRESULT>(hBrushLabel);
}
else break;
If you invalidate more than one label at a time, then one variable like this is not enough. You need to have a list/array/queue of IDs.

Marius answered your question - you are misusing the parameters of WM_CTLCOLORSTATIC, which is why your painting is not working correctly.
I would suggest a different solution to your problem. Have a list of colors, one set of Text/BkGnd colors for each label. Make changecolor() update the color entries for just the specified label as needed and then invalidate that label to trigger a repaint. WM_CTLCOLORSTATIC can then use the current colors of whichever label is currently being painted. No need to keep track of the changed Control ID between the call to changecolor() and the triggering of WM_CTLCOLORSTATIC (doing so is error prone anyway - think of what would happen if you wanted to change another label's coloring before WM_CTLCOLORSTATIC of a previous change is processed).
I would suggest a std::map to associate each label HWND to a struct holding that label's colors, eg:
#include <map>
struct sLabelColors
{
COLORREF clrText;
COLORREF clrBkGnd;
HBRUSH hBrushBkGnd;
};
std::map<HWND, sLabelColors> labelColors;
hWndLabel[0][0] = CreateWindowEx(...);
if (hWndLabel[0][0] != NULL)
{
sLabelColors &colors = labelColors[hWndLabel[0][0]];
colors.clrText = GetSysColor(COLOR_WINDOWTEXT);
colors.clrBkGnd = GetSysColor(COLOR_WINDOW);
colors.hBrushBkGnd = NULL;
}
case WM_CTLCOLORSTATIC:
{
HDC hdc = reinterpret_cast<HDC>(wParam);
sLabelColors &colors = labelColors[(HWND)lParam];
SetTextColor(hdc, colors.clrText);
SetBkColor(hdc, colors.clrBkGnd);
if (!colors.hBrushBkGnd) colors.hBrushBkGnd = CreateSolidBrush(colors.clrBkGnd);
return reinterpret_cast<LRESULT>(colors.hBrushBkGnd);
}
case WM_PARENTNOTIFY:
{
if (LOWORD(wParam) == WM_DESTROY)
{
HWND hWnd = (HWND)lParam;
std::map<HWND, sLabelColors>::iterator iter = labelColors.find((HWND)lParam);
if (iter != labelColors.end())
{
if (iter->hBrushBkGnd) DeleteObject(iter->hBrushBkGnd);
labelColors.erase(iter);
}
}
break;
}
DWORD WINAPI changecolor(LPVOID lpParameter)
{
sLabelColors &colors = labelColors[hWndLabel[0][0]];
if (colors.hBrushBkGnd) {
DeleteObject(colors.hBrushBkGnd);
colors.hBrushBkGnd = NULL;
}
colors.clrBkGnd = RGB(255, 255, 0x00);
InvalidateRect(hWndLabel[0][0], NULL, TRUE);
return 0;
}

Related

How to get window position of other program when the program is in expand monitor?

I want to detect whether a program is full screen in the expand monitor. I have got the expand monitor position using EnumDisplayMonitors. So if I get the program's position, I can compare it with expand monitor's position and get the result.
So I get the HWND of the program, and then I use ::GetWindowRect(HWND, &rect); But the rect is not correct.
HWND g_HWND = NULL;
BOOL CALLBACK EnumWindowsProcMy(HWND hwnd, LPARAM lParam)
{
DWORD lpdwProcessId;
GetWindowThreadProcessId(hwnd, &lpdwProcessId);
if (lpdwProcessId == lParam)
{
g_HWND = hwnd;
return FALSE;
}
return TRUE;
}
DWORD GetProcessidFromName(CString strName)
{
PROCESSENTRY32 pe;
DWORD id = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
pe.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hSnapshot, &pe))
{
return 0;
}
pe.dwSize = sizeof(PROCESSENTRY32);
while (Process32Next(hSnapshot, &pe) != FALSE)
{
CString strTmp = pe.szExeFile;
if (strName.CompareNoCase(strTmp) == 0)
{
id = pe.th32ProcessID;
break;
}
}
CloseHandle(hSnapshot);
return id;
}
CRect rect[2] = { (0,0,0,0),(0,0,0,0) }; //rect[1] stores the expand monitor's position
BOOL CALLBACK Monitorenumproc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
static BOOL first = FALSE;
MONITORINFO monitorinfo;
monitorinfo.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(hMonitor, &monitorinfo);
if (monitorinfo.dwFlags == MONITORINFOF_PRIMARY)
{
if (!first)
{
first = TRUE;
rect[0] = monitorinfo.rcMonitor;
return TRUE;
}
else
{
first = FALSE;
return FALSE;
}
}
else
{
rect[1] = monitorinfo.rcMonitor;
}
return TRUE;
}
...
//get the position of xxx.exe
EnumDisplayMonitors(NULL, NULL, Monitorenumproc, 0);
EnumWindows(EnumWindowsProcMy, GetProcessidFromName(_T("xxx.exe")));
RECT rect1;
::GetWindowRect(g_HWND, &rect1); //rect1 is not correct!
I'm not sure what exactly you mean by
But the rect is not correct.
but here is what I see may seem incorrect:
Negative values, which indicate the window position relative to the primary display. You have to do the [right-left, bottom-top] calculation to get the size.
Values larger than the display size which means the rect includes the area occupied by the drop shadow.
See the documentation of GetWindowRect
In Windows Vista and later, the Window Rect now includes the area
occupied by the drop shadow.
Calling GetWindowRect will have different behavior depending on
whether the window has ever been shown or not. If the window has not
been shown before, GetWindowRect will not include the area of the drop
shadow.
To get the window bounds excluding the drop shadow, use
DwmGetWindowAttribute, specifying DWMWA_EXTENDED_FRAME_BOUNDS. Note
that unlike the Window Rect, the DWM Extended Frame Bounds are not
adjusted for DPI. Getting the extended frame bounds can only be done
after the window has been shown at least once.
So use the snippet below to get the size without the drop shadow:
RECT dwmExtFrameBounds;
DwmGetWindowAttribute(g_HWND, DWMWINDOWATTRIBUTE::DWMWA_EXTENDED_FRAME_BOUNDS, &dwmExtFrameBounds, sizeof(RECT));
Bonus read: Why does a maximized window have the wrong window rectangle?

WM_PAINT: Manage hovering on an item of a tab control

So I'm overriding the WM_PAINT message of a tab control to add a close button, and to make a consistent look with the other controls of my application, I need to highlight the currently hovered item. The problem is the repainting does not work as expected, and I don't know how to manage the hovering state. The hovered item doesn't know when the mouse cursor has left it.
Here is a piece of code:
switch (msg) {
case WM_PAINT:
{
auto style = GetWindowLongPtr(m_self, GWL_STYLE);
// Let the system process the WM_PAINT message if the Owner Draw Fixed style is set.
if (style & TCS_OWNERDRAWFIXED) {
break;
}
PAINTSTRUCT ps{};
HDC hdc = BeginPaint(m_self, &ps);
RECT rc{};
GetClientRect(m_self, &rc);
// Paint the background
HBRUSH bkgnd_brush = GetSysColorBrush(COLOR_BTNFACE);
FillRect(hdc, &rc, bkgnd_brush);
DeleteObject(bkgnd_brush);
// Get infos about the control
int tabsCount = TabCtrl_GetItemCount(m_self);
int tabsSelect = TabCtrl_GetCurSel(m_self);
int ctl_identifier = GetDlgCtrlID(m_self);
// Draw each items
for (int i = 0; i < tabsCount; ++i) {
DRAWITEMSTRUCT dis{ ODT_TAB, ctl_identifier, static_cast<UINT>(i),
ODA_DRAWENTIRE, 0, m_self, hdc, RECT{}, 0 };
TabCtrl_GetItemRect(m_self, i, &dis.rcItem);
const UINT buffSize = 128;
wchar_t buff[buffSize];
TCITEM ti{};
ti.mask = TCIF_TEXT;
ti.pszText = buff;
ti.cchTextMax = buffSize;
this->Notify<int, LPTCITEM>(TCM_GETITEM, i, &ti); // Template class == SendMessageW
// Get item state
bool isHover = false;
HBRUSH hBrush = NULL;
POINT pt{};
GetCursorPos(&pt);
ScreenToClient(m_self, &pt);
// Item's bounds
if ((pt.x >= dis.rcItem.left && pt.x <= dis.rcItem.right) && (pt.y >= dis.rcItem.top && pt.y <= dis.rcItem.bottom)) {
m_hoveredTab = dis.rcItem;
isHover = true;
}
// Paint item according to its current state
hBrush = CreateSolidBrush(
(i == tabsSelect) ?
RGB(255, 131, 10) : isHover ?
RGB(255, 10, 73) : RGB(102, 10, 255));
FillRect(hdc, &dis.rcItem, hBrush);
DeleteObject(hBrush);
// Draw Text
SetBkMode(hdc, TRANSPARENT);
SetTextColor(hdc, RGB(0, 0, 0));
DrawTextW(hdc, buff, lstrlen(buff), &dis.rcItem, DT_SINGLELINE | DT_LEFT | DT_VCENTER);
}
EndPaint(m_self, &ps);
return 0;
}
// MOUSE EVENTS
case WM_MOUSEMOVE:
{
if (m_mouseTracking == FALSE) {
TRACKMOUSEEVENT trackMouseStruct{};
trackMouseStruct.cbSize = sizeof(trackMouseStruct);
trackMouseStruct.dwFlags = TME_HOVER | TME_LEAVE;
trackMouseStruct.hwndTrack = m_self;
trackMouseStruct.dwHoverTime = 1; // Shorter hover time to instantly hover a tab item
m_mouseTracking = TrackMouseEvent(&trackMouseStruct);
}
break;
}
case WM_MOUSEHOVER:
{
m_lostFocus = false;
break;
}
case WM_MOUSELEAVE:
{
m_mouseTracking = FALSE;
m_lostFocus = true;
break;
}
. . .
TrackMouseEvent detects hovering and leaving a window. The tab control is a single window that shows multiple tabs. If the cursor is hovering on one tab and is then moved to another tab (or to dead space in the tab control window), the TrackMouseEvent technique will not notify you.
Also, TrackMouseEvent could be interfering with the mouse tracking the tab control tries to do itself. Unfortunately, subclassing controls to modify their behavior usually requires knowing details of their implementation. For example, if you hadn't replaced the handling of WM_MOUSEMOVE, the tab control would probably do its own mouse tracking there in order to decide when to show its tooltip.
I think your best bet is to let the control process its messages as designed and to use the owner-draw mechanism to customize its appearance.
I finally managed to get something closer to the original control (even if there's a little bit of flicker, but it's pretty evident because the code below is just a "test" to understand how the tab control works.)
LRESULT TabsWindow::HandleMessage(UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
// Track the mouse cursor to check if it has hit a tab.
case WM_MOUSEMOVE:
{
if (_enableMouseTracking == FALSE) {
TRACKMOUSEEVENT trackMouseStruct{};
trackMouseStruct.cbSize = sizeof(trackMouseStruct);
trackMouseStruct.dwFlags = TME_LEAVE;
trackMouseStruct.hwndTrack = m_self;
_enableMouseTracking = TrackMouseEvent(&trackMouseStruct);
}
_prevHoverTabIndex = _hoverTabIndex;
POINT coordinates{ GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
_hoverTabIndex = this->GetTabIndexFrom(coordinates);
if (_hoverTabIndex != _prevHoverTabIndex) {
// We need to loop over tabs as we don't know which tab has the
// highest height, and of course, the width of each tab can vary
// depending on many factors such as the text width (Assuming the
// TCS_FIXEDWIDTH style was not set, but it'll work too...)
int count = this->Notify(TCM_GETITEMCOUNT, 0, 0);
RECT rc{ 0, 0, 0, 0 };
for (int i = 0; i != count; ++i) {
RECT currItm{};
this->Notify(TCM_GETITEMRECT, i, &currItm);
UnionRect(&rc, &currItm, &rc);
_tabBarRc = rc;
}
InvalidateRect(m_self, &rc, FALSE);
UpdateWindow(m_self);
}
}
return 0;
case WM_MOUSELEAVE: // The tab bar must be redrawn
{
_hoverTabIndex = -1;
InvalidateRect(m_self, &_tabBarRc, FALSE);
UpdateWindow(m_self);
_enableMouseTracking = FALSE;
}
return 0;
case WM_ERASEBKGND:
{
return TRUE;
}
case WM_PAINT:
{
auto style = GetWindowLongPtr(m_self, GWL_STYLE);
if ((style & TCS_OWNERDRAWFIXED)) {
break;
}
PAINTSTRUCT ps{};
HDC hdc = BeginPaint(m_self, &ps);
// Total Size
RECT rc{};
GetClientRect(m_self, &rc);
// Paint the background
HBRUSH bkgnd = GetSysColorBrush(COLOR_BTNFACE);
FillRect(hdc, &rc, bkgnd);
// Get some infos about tabs
int tabsCount = TabCtrl_GetItemCount(m_self);
int tabsSelect = TabCtrl_GetCurSel(m_self);
int ctl_identifier = GetDlgCtrlID(m_self);
for (int i = 0; i < tabsCount; ++i) {
DRAWITEMSTRUCT dis{ ODT_TAB, ctl_identifier, static_cast<UINT>(i), ODA_DRAWENTIRE, 0, m_self, hdc, RECT{}, 0 };
TabCtrl_GetItemRect(m_self, i, &dis.rcItem);
RECT intersect{}; // Draw the relevant items that needs to be redrawn
if (IntersectRect(&intersect, &ps.rcPaint, &dis.rcItem)) {
HBRUSH hBrush = CreateSolidBrush
(
(i == tabsSelect) ? RGB(255, 0, 255) : (i == _hoverTabIndex) ? RGB(0, 0, 255) : RGB(0, 255, 255)
);
FillRect(hdc, &dis.rcItem, hBrush);
DeleteObject(hBrush);
}
}
EndPaint(m_self, &ps);
return 0;
}
return DefSubclassProc(m_self, msg, lParam, wParam);
}
// Helpers to get the current hovered tab
int TabsWindow::GetTabIndexFrom(POINT& pt)
{
TCHITTESTINFO hit_test_info{};
hit_test_info.pt = pt;
return static_cast<int>(this->Notify(TCM_HITTEST, 0, &hit_test_info));
}
bool TabsWindow::GetItemRectFrom(int index, RECT& out)
{
if (index < -1) {
return false;
}
return this->Notify(TCM_GETITEMRECT, index, &out);
}
Explanations
The Tab Control, fortunately, provides ways to get the hovered item. First, TCM_HITTEST allows us to get the current index based on the passed RECT. TCM_GETITEMRECT does the opposite.
We need to track the mouse cursor to detect whether it is on a tab or not. The tab control does not seem to use WM_MOUSEHOVER at all, but it effectively uses WM_MOUSELEAVE as we can see on Spy++ with a standard tab control.
Firstly, I tried to "disable" the WM_MOUSEMOVE message, and the tab control was not responsible. However, when WM_MOUSELEAVE is disabled, it works as expected but does not update the window if the mouse cursor leaves the tab control (so, the focus effect sticks on the previously hovered tab, which is no longer).
Finally, everything depends on the WM_MOUSEMOVE event, and the WM_MOUSELEAVE message is not so big because it only handles the "focus exit state" of the tab control but is necessary to exit the hovered state of a tab.
Again, the above code is just a skeleton filled with problems, but it works and reproduces the same behavior as the stock control.

Redraw window using DirectX during move/resize

I've followed this tutorial and got it all working: http://www.braynzarsoft.net/index.php?p=InitDX11
The result is a window with a constantly changing background color. The trouble is that the color stops changing while the window is being dragged around. I've tried adding the following case statements (in various combinations) to the WndProc callback, but to no avail:
case WM_ENTERSIZEMOVE:
SetTimer(hwnd, 1, USER_TIMER_MINIMUM, NULL);
return 0;
case WM_EXITSIZEMOVE:
KillTimer(hwnd, 1);
return 0;
case WM_TIMER:
RedrawWindow(hwnd, NULL, NULL, RDW_INVALIDATE | RDW_INTERNALPAINT);
return 0;
case WM_PAINT:
UpdateScene();
DrawScene();
return 0;
The above causes an exception at d3d11DevCon->ClearRenderTargetView(renderTargetView, bgColor), but I've also tried merging the WM_PAINT case into the WM_TIMER case, and all I got was flickering between the natural window background color and the current color of the DX scene (the color of the DX portion of the flicker never evolved, it stayed constant no matter for how long I dragged the window).
Any tips?
A better option is to just not draw while in a resize. There's not usually a lot of value in having the backbuffer resized over and over again. Just wait until the resize is complete to resize the buffer.
static bool s_in_sizemove = false;
static bool s_in_suspend = false;
static bool s_minimized = false;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_SIZE:
if (wParam == SIZE_MINIMIZED)
{
if (!s_minimized)
{
s_minimized = true;
if (!s_in_suspend)
OnSuspending();
s_in_suspend = true;
}
}
else if (s_minimized)
{
s_minimized = false;
if (s_in_suspend)
OnResuming();
s_in_suspend = false;
}
else if ( !s_in_sizemove )
OnWindowSizeChanged();
break;
case WM_ENTERSIZEMOVE:
s_in_sizemove = true;
break;
case WM_EXITSIZEMOVE:
s_in_sizemove = false;
OnWindowSizeChanged();
break;
case WM_GETMINMAXINFO:
{
auto info = reinterpret_cast<MINMAXINFO*>(lParam);
info->ptMinTrackSize.x = 320;
info->ptMinTrackSize.y = 200;
}
break;
You have to release all the backbuffer and depth-buffer references and recreate them in OnWindowSizedChange.
The actual rendering is done as part of the message pump for most 'real-time' graphics apps:
// Main message loop
MSG msg = { 0 };
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
Tick();
}
}
Here Tick handles a timer update and the render.
See the Direct3D Win32 Game Visual Studio template for a complete example.
Update: If the 'blank window' bothers you during the resize, but you are fine with the default behavior of DXGI_SCALING_STRETCH during the resize, you can replace the WM_PAINT above with:
case WM_PAINT:
if (s_in_sizemove)
{
game->Tick();
}
else
{
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
break;
I had same problem. I thought solution would be complicated. However, no. That is about mesage pool. DX should use same thread and indeed you use your rendering (Ex: myRender(){..} ) in that loop In my case Frame(); is the bool returnable I use for rendering that contains all operatios :
MSG msg;
bool done, result;
// Initialize the message structure.
ZeroMemory(&msg, sizeof(MSG));
// Loop until there is a quit message from the window or the user.
done = false;
while (!done)
{
// Handle the windows messages.
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// If windows signals to end the application then exit out.
if (msg.message == WM_QUIT)
{
done = true;
}
else
{
// Otherwise do the frame processing.
result = Frame();
if (!result)
{
done = true;
}
}
}
When you resize you can handle some messages WM_SIZE or WM_MOVE message. In your LRESULT CALLBACK handle:
LRESULT CALLBACK WndProc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam) {
//...OTHERS...
if (umessage == WM_MOVE) {
/*Dont be confused ApplicationHandle is pointer of my SystemClass
which set ApplicationHandle = this in SystemClass.
to create a window/s and Graphics (contains all DirectX related operations).
Here GraphicsClass (contains all DX calls) initialized in
SystemClass as new class and SystemClass initialized as
new class at main.cpp in WINAPI. That makes a lot easier
for handling this kind of issues for me
In your case you will call your rendering loop instead Frame();*/
if (ApplicationHandle -> m_Graphics) {
RECT r;
GetClientRect(ApplicationHandle -> m_hwnd, & r);
ApplicationHandle -> m_Graphics -> clientSize = {
r.right - r.left,
r.bottom - r.top
};
//frame processing.
ApplicationHandle -> m_Graphics -> Frame();
}
if (umessage == WM_SIZING) {
if ((wparam == WMSZ_BOTTOM || wparam == WMSZ_RIGHT || wparam == WMSZ_BOTTOMRIGHT) && ApplicationHandle -> m_Graphics) {
/*IF WE DO NOT HANDLE wparam resize will be very laggy.*/
GetClientRect(ApplicationHandle -> m_hwndOWNER, & clientRect);
ApplicationHandle -> m_Graphics -> clientSize = {
clientRect.right - clientRect.left,
clientRect.bottom - clientRect.top
};
ApplicationHandle -> m_Graphics -> Frame();
}
}
}
//...OTHERS...
}
HERE IS A VIDEO OF RESULT: https://www.youtube.com/watch?v=vN_XPVRHuiw&feature=youtu.be
even if you are drawing custom window using Desktop Window Manager (WDM) you can handle WM_NCHITTEST for other click situations as that will only update if you resize and move but not if you click and hold caption or hold border only.
additionally, I did not get that why you handle WM_PAINT if you are using DirectX already.

win32 bitmaps flashing when more than one sprite on screen

I've been using the win32 api to make a game with sprites. For some reason when I have more than one sprite on screen they flash occasionally as if they are disappearing and returning. When there is only one sprite on screen it displays correctly.
I am using C++, win32 API and working with Visual Studio 08
The following is roughly what I have:
//creates rect based on window client area
GetClientRect(ghwnd, &screenRect);
// Initialises front buffer device context (window)
frontHDC = GetDC(ghwnd);
// sets up Back DC to be compatible with the front
backHDC = CreateCompatibleDC(frontHDC);
// Create another hdc to store the bitmap in before the backbuffer
bitmapHDC = CreateCompatibleDC(frontHDC);
//creates bitmap compatible with the front buffer
theOldFrontBitMap = CreateCompatibleBitmap(frontHDC, screenRect.right, screenRect.bottom);
//creates bitmap compatible with the back buffer
theOldBackBitMap = (HBITMAP)SelectObject(backHDC, theOldFrontBitMap);
HBITMAP originalBitMap = (HBITMAP)SelectObject(bitmapHDC,bitmap);
//Transparency function
TransparentBlt( backHDC,
m_Position.x,
m_Position.y,
m_Size.x,
m_Size.y,
bitmapHDC,
0,
0,
m_Size.x,
m_Size.y,
0x00FFFFFF);
SelectObject(bitmapHDC,originalBitMap);
BitBlt(frontHDC, screenRect.left, screenRect.top,
screenRect.right, screenRect.bottom, backHDC, 0, 0, SRCCOPY);
Am I doing this correctly? and if so where am I going wrong? If I have not given enough information please tell me and I will rectify that.
The problem with creating a Win32 game is that, even if you use double buffering, you have no way to wait for the vertical retrace of the monitor to display the buffer.
Displaying the buffer or sprite while the vertical retrace is in progress can cause tearing or even the disappearing sprite that you experience.
The only real way around this is to use an SDK like OpenGL or DirectX to manage and display the buffers.
Here's a sample program that may help you, use the arrow keys to move the white box on the double buffered background:
#include <Windows.h>
RECT rcSize;
HDC hdcBackBuffer, hdcSprite;
HBITMAP hbmBackBuffer, hbmSprite;
int spriteX = 175, spriteY = 175;
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static PAINTSTRUCT ps;
switch (msg)
{
case WM_CREATE:
{
HDC hdcWindow = GetDC(hWnd);
// make back buffer
GetClientRect(hWnd, &rcSize);
hdcBackBuffer = CreateCompatibleDC(hdcWindow);
hbmBackBuffer = CreateCompatibleBitmap(hdcBackBuffer, rcSize.right - rcSize.left, rcSize.bottom - rcSize.top);
SelectObject(hdcBackBuffer, hbmBackBuffer); // SHOULD SAVE PREVIOUS...
// make sprite
hdcSprite = CreateCompatibleDC(hdcWindow);
hbmSprite = CreateCompatibleBitmap(hdcSprite, 50, 50);
SelectObject(hdcSprite, hbmSprite); // SHOULD SAVE PREVIOUS...
RECT rcSprite;
SetRect(&rcSprite, 0, 0, 50, 50);
FillRect(hdcSprite, &rcSprite, (HBRUSH)GetStockObject(WHITE_BRUSH));
ReleaseDC(hWnd, hdcWindow);
return 0;
}
case WM_KEYDOWN:
{
// SHOULD REALLY USE GetAsyncKeyState for game, but simplified here
switch (wParam)
{
case VK_LEFT:
spriteX--;
break;
case VK_RIGHT:
spriteX++;
break;
case VK_UP:
spriteY--;
break;
case VK_DOWN:
spriteY++;
break;
}
return 0;
}
case WM_ERASEBKGND:
{
return 1; // INDICATE THAT WE ERASED THE BACKGROUND OURSELVES
}
case WM_PAINT:
{
BeginPaint(hWnd, &ps);
// clear back buffer
FillRect(hdcBackBuffer, &rcSize, (HBRUSH)GetStockObject(BLACK_BRUSH));
// render sprite to back buffer
BitBlt(hdcBackBuffer, spriteX, spriteY, 50, 50, hdcSprite, 0, 0, SRCCOPY);
// render back buffer to screen
BitBlt(ps.hdc, 0, 0, rcSize.right - rcSize.left, rcSize.bottom - rcSize.top, hdcBackBuffer, 0, 0, SRCCOPY);
EndPaint(hWnd, &ps);
return 0;
}
case WM_DESTROY:
{
// TODO - DESTROY ALL BITMAPS AND DEVICE CONTEXTS
PostQuitMessage(0);
return 0;
}
default:
{
return DefWindowProc(hWnd, msg, wParam, lParam);
}
}
}
int WINAPI WinMain(HINSTANCE hPrevInstance, HINSTANCE hInstance, LPSTR lpCmdLine, int nShowCmd)
{
static TCHAR className[] = TEXT("GameClass");
static TCHAR windowName[] = TEXT("A Game");
WNDCLASSEX wcex;
wcex.cbClsExtra = 0;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.cbWndExtra = 0;
wcex.hbrBackground = NULL;
wcex.hCursor = LoadCursor(hInstance, IDC_ARROW);
wcex.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
wcex.hIconSm = NULL;
wcex.hInstance = hInstance;
wcex.lpfnWndProc = WndProc;
wcex.lpszClassName = className;
wcex.lpszMenuName = NULL;
wcex.style = 0;
if (!RegisterClassEx(&wcex))
return 0;
HWND hWnd = CreateWindow(className, windowName, WS_CAPTION | WS_BORDER | WS_SYSMENU, 0, 0, 400, 400, NULL, NULL, hInstance, NULL);
if (!hWnd)
return 0;
ShowWindow(hWnd, nShowCmd);
UpdateWindow(hWnd);
MSG msg;
for (;;)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
InvalidateRect(hWnd, NULL, FALSE);
}
return msg.wParam;
}
I think your back buffer implementation is wrong although Im not sure exactly where. Try this implementation of a separate back buffer class. I hope it helps.
Here my back buffer class.
#ifndef BACKBUFFER_H
#define BACKBUFFER_H
#include <Windows.h>
class BackBuffer
{
public:
BackBuffer(HWND hWnd, int width, int height);
~BackBuffer();
HDC getDC();
int width();
int height();
void present();
private:
// Make copy constructor and assignment operator private
// so client cannot copy BackBuffers. We do this because
// this class is not designed to be copied because it
// is not efficient--copying bitmaps is slow (lots of memory).
// In addition, most applications will probably only need one
// BackBuffer anyway.
BackBuffer(const BackBuffer& rhs);
BackBuffer& operator=(const BackBuffer& rhs);
private:
HWND mhWnd;
HDC mhDC;
HBITMAP mhSurface;
HBITMAP mhOldObject;
int mWidth;
int mHeight;
};
#endif //BACKBUFFER_H
Heres the implementation:
BackBuffer::BackBuffer(HWND hWnd, int width, int height)
{
//Save a copy of the main window handle
mhWnd = hWnd;
//Get a handle to the device context associated with
// the window
HDC hWndDC = GetDC(hWnd);
//Save the backbuffer dimensions
mWidth = width;
mHeight = height;
//Create system memory device context that is compatible
//with the window one
mhDC = CreateCompatibleDC(hWndDC);
//Create the backbuffer surface bitmap that is compatible
//with the window device context bitmap format. That is
//the surface we will render onto.
mhSurface = CreateCompatibleBitmap(hWndDC, width, height);
//Done with DC
ReleaseDC(hWnd, hWndDC);
//At this point, the back buffer surface is uninitialized,
//so lets clear it to some non-zero value. Note that it
//needs to be a non-zero. If it is zero then it will mess
//up our sprite blending logic.
//Select the backbuffer bitmap into the DC
mhOldObject = (HBITMAP)SelectObject(mhDC, mhSurface);
//Select a white brush
HBRUSH white = (HBRUSH)GetStockObject(WHITE_BRUSH);
HBRUSH oldBrush = (HBRUSH)SelectObject(mhDC, white);
//Clear the backbuffer rectangle
Rectangle(mhDC, 0, 0, mWidth, mHeight);
//Restore the original brush
SelectObject(mhDC, oldBrush);
}
BackBuffer::~BackBuffer()
{
SelectObject(mhDC, mhOldObject);
DeleteObject(mhSurface);
DeleteDC(mhDC);
}
HDC BackBuffer::getDC()
{
return mhDC;
}
int BackBuffer::width()
{
return mWidth;
}
int BackBuffer::height()
{
return mHeight;
}
void BackBuffer::present()
{
//Get a handle to the device context associated with
//the window
HDC hWndDC = GetDC(mhWnd);
//Copy the backbuffer contents over to the
//window client area
BitBlt(hWndDC, 0, 0, mWidth, mHeight, mhDC, 0, 0, SRCCOPY);
//Free window DC when done
ReleaseDC(mhWnd, hWndDC);
}
Try to work your way through this implementation the comments should help you understand. Hope this helps.

Handling WM_NCPAINT "breaks" DWM glass rendering on Vista/Aero

I am trying to make a window that alternates between having an Aero/Glass and a custom rendered frame (by handling WM_NCPAINT) based on a user setting. (Windows Vista).
DwmComposition is enabled. My app comes up with the glass frame, but as soon as I toggle the setting to trigger the custom WM_NCPAINT codepath then toggle back to use DefWindowProc's WM_NCPAINT handling, the native frame is now perpetually stuck in the "Vista Basic" style - it's no longer translucent and the caption buttons look different to the normal Aero/Glass ones.
I've tried just about every way of poking the window from sending SWP_FRAMECHANGED to changing the window style then changing it back, hiding it, etc, but all to no avail. It seems like as soon as I handle WM_NCPAINT for a glass window rather than deferring to DefWindowProc my window is forever "broken".
I found a C#/WPF example on MSDN (code dot msdn dot microsoft dot com slash chrome ) that seemed to indicate that one simply needed to stop handling WM_NCPAINT and the glass would return, but that does not seem to work in my own app.
Is there a way to reset this state cleanly? My code is in C++ and lives here:
http://bengoodger.dreamhosters.com/software/chrome/dwm/
#include <windows.h>
#include <dwmapi.h>
static const wchar_t* kWindowClass = L"BrokenGlassWindow";
static const wchar_t* kWindowTitle =
L"BrokenGlass - Right click client area to toggle frame type.";
static const int kGlassBorderSize = 50;
static const int kNonGlassBorderSize = 40;
static bool g_glass = true;
bool IsGlass() {
BOOL composition_enabled = FALSE;
return DwmIsCompositionEnabled(&composition_enabled) == S_OK &&
composition_enabled && g_glass;
}
void SetIsGlass(bool is_glass) {
g_glass = is_glass;
}
void ToggleGlass(HWND hwnd) {
SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
RedrawWindow(hwnd, NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM w_param,
LPARAM l_param) {
PAINTSTRUCT ps;
HDC hdc;
RECT wr;
HBRUSH br;
RECT* nccr = NULL;
RECT dirty;
RECT dirty_box;
MARGINS dwmm = {0};
WINDOWPOS* wp = NULL;
switch (message) {
case WM_CREATE:
SetCursor(LoadCursor(NULL, IDC_ARROW));
break;
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &wr);
br = GetSysColorBrush(IsGlass() ? COLOR_APPWORKSPACE : COLOR_WINDOW);
FillRect(hdc, &wr, br);
EndPaint(hwnd, &ps);
break;
case WM_NCPAINT:
if (IsGlass())
return DefWindowProc(hwnd, message, w_param, l_param);
GetWindowRect(hwnd, &wr);
if (!w_param|| w_param == 1) {
dirty = wr;
dirty.left = dirty.top = 0;
} else {
GetRgnBox(reinterpret_cast<HRGN>(w_param), &dirty_box);
if (!IntersectRect(&dirty, &dirty_box, &wr))
return 0;
OffsetRect(&dirty, -wr.left, -wr.top);
}
hdc = GetWindowDC(hwnd);
br = CreateSolidBrush(RGB(255,0,0));
FillRect(hdc, &dirty, br);
DeleteObject(br);
ReleaseDC(hwnd, hdc);
break;
case WM_NCACTIVATE:
// Force paint our non-client area otherwise Windows will paint its own.
RedrawWindow(hwnd, NULL, NULL, RDW_UPDATENOW);
break;
case WM_NCCALCSIZE:
nccr = w_param ? &reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0]
: reinterpret_cast<RECT*>(l_param);
nccr->bottom -= IsGlass() ? kGlassBorderSize : kNonGlassBorderSize;
nccr->right -= IsGlass() ? kGlassBorderSize : kNonGlassBorderSize;
nccr->left += IsGlass() ? kGlassBorderSize : kNonGlassBorderSize;
nccr->top += IsGlass() ? kGlassBorderSize : kNonGlassBorderSize;
return WVR_REDRAW;
case WM_RBUTTONDOWN:
SetIsGlass(!g_glass);
ToggleGlass(hwnd);
break;
case 0x31E: // WM_DWMCOMPOSITIONCHANGED:
ToggleGlass(hwnd);
break;
case 0xAE: // WM_NCUAHDRAWCAPTION:
case 0xAF: // WM_NCUAHDRAWFRAME:
return IsGlass() ? DefWindowProc(hwnd, message, w_param, l_param) : 0;
case WM_WINDOWPOSCHANGED:
dwmm.cxLeftWidth = kGlassBorderSize;
dwmm.cxRightWidth = kGlassBorderSize;
dwmm.cyTopHeight = kGlassBorderSize;
dwmm.cyBottomHeight = kGlassBorderSize;
DwmExtendFrameIntoClientArea(hwnd, &dwmm);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, w_param, l_param);
}
return 0;
}
ATOM RegisterClazz(HINSTANCE instance) {
WNDCLASSEX wcex = {0};
wcex.cbSize = sizeof(wcex);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = instance;
wcex.lpszClassName = kWindowClass;
return RegisterClassEx(&wcex);
}
int WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, int show_command) {
RegisterClazz(instance);
HWND hwnd = CreateWindow(kWindowClass, kWindowTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL,
instance, NULL);
ShowWindow(hwnd, show_command);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return static_cast<int>(msg.wParam);
}
When toggling between Aero/Glass and your custom rendered frame it you can use the following to explicitly control the non-client area rendering policy:
DWMNCRENDERINGPOLICY policy = DWMNCRP_ENABLED; // DWMNCRP_DISABLED to toggle back
DwmSetWindowAttribute(hwnd,
DWMWA_NCRENDERING_POLICY,
(void*)&policy,
sizeof(DWMNCRENDERINGPOLICY));

Resources