My dialog box displays the current selected audio input in the manner that Sound manager does in Windows Vista:
Here's my WIN32 dialogbox. The desired location of the shape is pointed at with an arrow:
What is the best strategy for painting this shape. Custom drawn control? GDI?
Note that the application is practically done (So no WPF nor Direct2D) and that the color is given in COLORREF so there's no option to prepare a list of icons to choose from.
\\\\\\\\\\ EDIT[1] \\\\\\\\\\\\\\
I've made some additional investigations. It seems like GDI was replaced by GDI+ which is simpler to use and has antialiasing and Alpha which are important to me.
If you take a closer look at the image they use in the Sound Manager you'll see for yourself:
So I've written GDI+ code and it works OK. That is, the image is reasonable but I create the whole bitmap it with every WM_PAINT, which is ugly.
I did not find a way (In GDI+) to create a bitmap in memory (Equivalent of CreateCompatibleDC) then to copy it to target (Equivalent of BitBlt). I've seen examples that mix GDI and GDI+. Is it the correct way to go?
The best strategy is draw using GDI an HBITMAP that will act as buffer, every time the color changed just recreate that bitmap. Then in WndProc of shape when WM_PAINT of controls is made just draw it:
case WM_PAINT:
PAINTSTRUCT ps;
HDC hdc;
BITMAP bitmap;
HDC hdcMem;
HGDIOBJ oldBitmap;
hdc = BeginPaint(hWnd, &ps);
hdcMem = CreateCompatibleDC(hdc);
oldBitmap = SelectObject(hdcMem, hBitmap);
GetObject(hBitmap, sizeof(bitmap), &bitmap);
BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, oldBitmap);
DeleteDC(hdcMem);
EndPaint(hWnd, &ps);
break;
For the simplicity of desired drawing (a circle inside a circle) you could draw it all in WM_PAINT, but it's a good practice to create a buffer as suggested that is faster and will avoid flickering and also will allow you to draw parts and not entire image. To create the buffer use: CreateCompatibleBitmap create a memory DC:
HDC hDC;
int width = 16;
int height= 16;
HDC hMemDC = ::CreateCompatibleDC(NULL);
HBITMAP hBmp = ::CreateCompatibleBitmap(hDC, width, height);
::SelectObject(hMemDC, hBmp);
And draw using WINAPI, take a look at Win32 GDI Drawing a circle
If you want to draw from a resource, in WM_CREATE load the bitmap:
HBITMAP g_hbmBall = NULL;
case WM_CREATE:
g_hbmBall = LoadBitmap(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_BALL));
if(g_hbmBall == NULL)
MessageBox(hwnd, "Could not load IDB_BALL!", "Error", MB_OK | MB_ICONEXCLAMATION);
break;
Then just draw on WM_PAINT:
case WM_PAINT:
{
BITMAP bm;
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = SelectObject(hdcMem, g_hbmBall);
GetObject(g_hbmBall, sizeof(bm), &bm);
BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
EndPaint(hwnd, &ps);
}
break;
Just because its a small icon you can do all drawing on WM_PAINT of window's WndProc... but just to avoid to create another control and because it's a small bitmap.
Hope It Helps!
EDIT
If you plan to use GDI+ (I though you weren't interested on it... i'm sorry). Sure, you can draw a bitmap using GDI+. All the things change to draw you only need to create a Graphics and make drawings. Also, you can load a Bitmap and draw it using `DrawImage', example taken from MSDN:
Image image(L"Grapes.jpg");
graphics.DrawImage(&image, 60, 10);
When you are on WinProc you can create a Graphics from hDC and then paint. Remember to dispose the Graphics and don't make call to base WinProc.
MSDN Reference
Related
I'm trying to make the snippingtool in c++. I managed to create a borderless, fullscreen window via this code;
WindProc:
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
switch (message)
{
case WM_CHAR: //this is just for a program exit besides window's borders/taskbar
if (wparam==VK_ESCAPE)
{
DestroyWindow(hwnd);
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wparam, lparam);
}
}
Creating the window;
WNDCLASS windowClass={0};
windowClass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
windowClass.hCursor=LoadCursor(NULL, IDC_ARROW);
windowClass.hInstance=NULL;
windowClass.lpfnWndProc=WndProc;
windowClass.lpszClassName=TEXT("Window in Console"); //needs to be the same name
//when creating the window as well
windowClass.style=CS_HREDRAW | CS_VREDRAW;
//also register the class
if (!RegisterClass(&windowClass))
MessageBoxA(NULL, "Could not register class", "Error", MB_OK);
HWND windowHandle=CreateWindowA("Window in Console",
NULL,
WS_POPUP, //borderless
0, //x coordinate of window start point
0, //y start point
GetSystemMetrics(SM_CXSCREEN), //width of window
GetSystemMetrics(SM_CYSCREEN), //height of the window
NULL, //handles and such, not needed
NULL,
NULL,
NULL);
ShowWindow(windowHandle, SW_RESTORE);
Whats left to do is now taking the screenshot of the screen and drawing it on form. Which i fail at this part.
When i googled, i first saw SetPixel function but to draw the form it took like half a minute. it was veerry slow. Then people said use Device Context (its the forms' drawing data in the memory as i understood) and draw on that, it will be much quicker then just update the window. And here's what i did;
int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
HDC hdc = GetDC(windowHandle);
BitBlt(hdc, 0, 0, nScreenWidth, nScreenHeight, GetDC(NULL), 0, 0, SRCCOPY | CAPTUREBLT);
UpdateWindow(windowHandle);
ShowWindow(windowHandle, SW_RESTORE);
UpdateWindow(windowHandle);
As you can guess, it didn't work. My form is blank white. I don't understand if i should write this on WM_PAINT message on WindProc or not. I tried many variations to this and actually one point it worked i guess but then stopped working when i changed something and i couldn't get it to work again...
thank you.
Thanks for the comments, i did some more research on WM_PAINT message. And i found this golden document:
http://www.winprog.org/tutorial/bitmaps.html
My code in the original post stays the same, i only added 2 things;
1-Taking a screenshot of the screen and saving it;
(got it from here:
How can I take a screenshot in a windows application?)
// get the device context of the screen
HDC hScreenDC = GetDC(NULL);
// and a device context to put it in
HDC hMemoryDC = CreateCompatibleDC(hScreenDC);
int width = GetSystemMetrics(SM_CXSCREEN);
int height = GetSystemMetrics(SM_CYSCREEN);
// hBitmap is a HBITMAP that i declared globally to use within WM_PAINT
// maybe worth checking these are positive values
hBitmap = CreateCompatibleBitmap(hScreenDC, width, height);
// get a new bitmap
HBITMAP hOldBitmap = (HBITMAP) SelectObject(hMemoryDC, hBitmap);
BitBlt(hMemoryDC, 0, 0, width, height, hScreenDC, 0, 0, SRCCOPY);
hBitmap = (HBITMAP) SelectObject(hMemoryDC, hOldBitmap);
// clean up
DeleteDC(hMemoryDC);
ReleaseDC(NULL,hScreenDC);
// now your image is held in hBitmap. You can save it or do whatever with it
2- Painting via WM_PAINT:
switch (message)
{
case WM_PAINT:{
int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
BITMAP bm;
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = (HBITMAP) SelectObject(hdcMem, hBitmap);
GetObject(hBitmap, sizeof(bm), &bm);
BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
EndPaint(hwnd, &ps);
}
return 0;
Note that i'm totally new to GDI, window stuff. I just kinda mashed pieces together i found here and there, but it works xd
thanks all for the help.
EDIT: also, just a quick info. If your display settings have some kinda scaling, screenshots are also scaled. What this means is if you have per se 125% scaling, then the screenshot will not be the actual fullscreen. To prevent this you need to have a manifest file.
https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests
the setting we are looking for is DPI awareness. here's my manifest file;
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" >
<asmv3:application>
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
<dpiAware>true</dpiAware>
</asmv3:windowsSettings>
</asmv3:application>
</assembly>
my .rc file:
#include "winuser.h"
1 RT_MANIFEST scanner.exe.manifest
1. Problem
I have two buffers. Primary buffer, which is displayed on the screen and a secondary buffer where everything is drawn and then passed to the primary.
The Graphics object is created from the secondary buffer, which is associated with a bitmap of size 800x600. Naturally when you resize the window, the size of the bitmap has to change in order to prevent clipping issues.
The secondary HDC gets updated, and the bitmap is copied to the primary.
The issue is that there is something left in the Graphics object associated with secondary HDC that generates clipping. The drawing region still stays 800x600 despite already being updated to something larger (1000x1000).
My question is what should I update inside the Graphics object (Without having to explicitly recreate it from the existing HDC) in order to make it's drawing region fit the bitmap size.
2. What I tried
The first thing I tried was recreating the Graphics object from the updated HDC. This method works and the drawing region fits the size of the bitmap. It does not meet the design standard however. Graphics should be reusable.
I also tried updating the clipping region of the graphics object using the SetClip method. Although that did not seem to be the problem.
This is how I create the buffers.
HDC CoreWindowFrame::InitPaint(HWND hWnd)
{
windowHdc = GetDC(hWnd);
HDC secondaryBuffer = CreateCompatibleDC(windowHdc);
HBITMAP map = CreateCompatibleBitmap(windowHdc, width, height);
SelectObject(secondaryBuffer, map);
return secondaryBuffer;
}
This function is called on resize
void CoreWindowFrame::UpdateBitmap(int width, int height)
{
HBITMAP map = CreateCompatibleBitmap(windowHdc, width, height);
SelectObject(secondaryBuffer, map);
}
And this is message processing:
case WM_SIZE:
ConsoleWrite("WM_SIZE RECIEVED");
width = *((unsigned short*)&lParam);
height = ((unsigned short*)&lParam)[1];
UpdateBitmap(width, height);
break;
case WM_PAINT:
ConsoleWrite("WM_PAINT RECIEVE");
windowGraphics->Clear(Color(255, 255, 255));
Pen* testPen = new Pen(Color(255, 0, 0), 1.0F);
windowGraphics->DrawLine(testPen, 0, 0, calls*3, 100);
BitBlt(windowHdc, 0, 0, updatedWidth, updatedHeight, secondaryBuffer, 0, 0, MERGECOPY);
3. Expected Result
The graphics object should be reusable and it should not be tossed away and replaced with a new one each time something is refreshed. Therefore it has to be updated accordingly in case anything is resized or changed. I expect the region to fit the size of the currently updated bitmap in the secondary HDC. The bitmap, as seen in the code, is updated properly. It is the Graphics object that does not. It acts like it still remembers some of the value from the previous BitMap which results in this behavior.
windowHdc = GetDC(hWnd);
HDC secondaryBuffer = CreateCompatibleDC(windowHdc);
HBITMAP map = CreateCompatibleBitmap(windowHdc, width, height);
SelectObject(secondaryBuffer, map);
return secondaryBuffer;
HDC obtained from GetDC or BeginPaint cannot be reused, as noted in comments.
You can however reuse memory bitmap (from CreateCompatibleBitmap) and reuse memory dc (obtained from CreateCompatibleDC), although there is usually no point in reusing memory dc.
Moreover, cleanup is required to avoid resource leak. Call ReleaseDC when you are finished with GetDC. See documentation for relevant release/delete functions.
Do this for a simple paint routine:
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
Gdiplus::Graphics gr(hdc);
Gdiplus::Pen testPen(Gdiplus::Color(255, 0, 0), 1.0F);
gr.Clear(Gdiplus::Color::White);
gr.DrawLine(&testPen, 0, 0, 100, 100);
EndPaint(hwnd, &ps);
return 0;
}
Usually you don't need to do anything more. Just call InvalidateRect in response to WM_SIZE to update paint.
For double-buffering, or drawing on a canvas, you can create a memory bitmap and reuse it. If window size changes, then you have to call DeleteObject for the old bitmap, and create a new bitmap based on the new size. Or you can create a bitmap which matches the largest window size, then use this bitmap for all window sizes.
See the example below for double-buffer paint (however reusing hbitmap is not necessary in this case)
HBITMAP hbitmap = NULL;
void InitPaint(HWND hwnd)
{
HDC hdc = GetDC(hwnd);
//create a bitmap with max size:
int w = GetSystemMetrics(SM_CXFULLSCREEN);
int h = GetSystemMetrics(SM_CYFULLSCREEN);
hbitmap = CreateCompatibleBitmap(hdc, w, h);
ReleaseDC(hwnd, hdc);
}
void cleanup()
{
if (hbitmap)
DeleteObject(hbitmap);
}
...
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
RECT rc; GetClientRect(hwnd, &rc);
int w = rc.right;
int h = rc.bottom;
HDC memdc = CreateCompatibleDC(hdc);
HBITMAP oldbmp = (HBITMAP)SelectObject(memdc, hbitmap);
Gdiplus::Graphics gr(memdc);
Gdiplus::Pen testPen(Gdiplus::Color(255, 0, 0), 1.0F);
gr.Clear(Gdiplus::Color(255, 255, 255));
gr.DrawLine(&testPen, 0, 0, w, h);
BitBlt(hdc, 0, 0, w, h, memdc, 0, 0, SRCCOPY);
//cleanup:
SelectObject(memdc, oldbmp);
DeleteDC(memdc);
EndPaint(hwnd, &ps);
return 0;
}
Summary:
GetDC doesn't create anything. It only returns a reference to an existing handle which is used by the system. When you are finished with this handle, release it. There is no way to optimize this any further.
Other GDI objects, like pen or bitmap, can be created for your program and they can be reused. It only takes a few nano-seconds to create/destroy a pen, so it's usually not worth the added complexity to store these objects and keeping track.
The main bottle-neck is when you draw on the screen, for example drawing a line. You have to talk to the graphics card and talk to the monitor which takes a while. You can use double-buffering to draw on a bitmap, then BitBlt on the screen. BitBlt can be slow too, depending on the system.
For animation, use double-buffering if you see flicker.
For better performance you can use newer technologies like Direct2D
If animation is still too slow, consider using a second thread to run any math type calculations (the second thread should not reference any window handle, such as HDC from GetDC or BeginPaint)
I want to load a bitmap to a window in my application, I will use GDI to draw the bitmap to the window. Should I also draw the bitmap when handling the WM_PAINT message so that the bitmap persists on the window?
Yes, you should draw your bitmap in WM_PAINT or WM_ERASEBKGND handler just like this:
switch(Msg)
{
case WM_DESTROY:
PostQuitMessage(WM_QUIT);
break;
case WM_PAINT:
hDC = BeginPaint(hWnd, &Ps);
// Load the bitmap from the resource
bmp = LoadBitmap(hInst, MAKEINTRESOURCE(IDB_MY_COOL_PIC));
// Create a memory device compatible with the above DC variable
MemDC = CreateCompatibleDC(hDC);
// Select the new bitmap
HBITMAP hOldBmp = SelectObject(MemDC, bmp);
// Copy the bits from the memory DC into the current dc
BitBlt(hDC, 10, 10, 450, 400, MemDC, 0, 0, SRCCOPY);
// Restore the old bitmap
SelectObject(MemDC, hOldBmp);
DeleteObject(bmp);
DeleteDC(MemDC);
EndPaint(hWnd, &Ps);
break;
default:
return DefWindowProc(hWnd, Msg, wParam, lParam);
}
How to draw text with transparent color using WinAPI?
In usual way I used SetBkMode(hDC, TRANSPARENT), but now I need to use double buffer.
In this way images draws correct, but text draws not correct (with black background).
case WM_PAINT:
{
hDC = BeginPaint(hWnd, &paintStruct);
SetBkMode(hDC, TRANSPARENT);
HDC cDC = CreateCompatibleDC(hDC);
HBITMAP hBmp = CreateCompatibleBitmap(hDC, width, height);
HANDLE hOld = SelectObject(cDC, hBmp);
HFONT hFont = (HFONT)SelectObject(hDC, font);
SetTextColor(cDC, color);
SetBkMode(cDC, TRANSPARENT);
TextOut(cDC, 0, 0, text, wcslen(text));
SelectObject(cDC, hFont);
BitBlt(hDC, 0, 0, width, height, cDC, 0, 0, SRCCOPY);
SelectObject(cDC, hOld);
DeleteObject(hBmp);
DeleteDC(cDC);
EndPaint(hWnd, &paintStruct);
return 0;
}
SetBkMode(dc, TRANSPARENT) should work fine still. Make sure you're using the correct DC handle when drawing to your back buffer.
When you create a bitmap, the color isn't specified. The documentation doesn't state how it's initialized, but solid black (all zeros) seems likely. Since you're drawing the text on the bitmap, the background of the bitmap remains black. You then copy the entire bitmap to the DC and all the pixels come along, the background along with the text.
To fix this you must copy the desired background into the bitmap before you draw the text.
I'm trying to set pixel by mouse click, but nothing happens when I click. Here is part of my code.
First, I control window size changing in WM_SIZE.
Than, at first time when I want to set pixel by mouse I get window's width and height, then copy window's content to memory HDC and HBITMAP (in Store Window) (HBITMAP size equal to (width,height)). In fact, I copy to memory only clear window.
And than in any case I set pixel to memory DC. In next WM_PAINT message handling I'm drawing memory DC to screen.
.....
case WM_SIZE:
{
CheckWidthHeight();
break;
}
case WM_MBUTTONDOWN:
{
if (firstTimeDraw)
{
CheckWidthHeight();
StoreWindow();
firstTimeDraw = false;
}
SetPixel(memoryDC, LOWORD(lParam), HIWORD(lParam), RGB(0,0,0));
break;
}
case WM_PAINT:
{
RestoreWindow();
break;
}
.....
where my functions and variables is:
HDC memoryDC;
HBITMAP memoryBitmap;
int width = 0, height = 0;
bool firstTimeDraw = true;
void CheckWidthHeight()
{
RECT clientRect;
GetClientRect(hwnd, &clientRect);
width = clientRect.right - clientRect.left;
height = clientRect.bottom - clientRect.top;
}
//Copy real window content to memory window
void StoreWindow()
{
HDC hDC = GetDC(hwnd);
memoryDC = CreateCompatibleDC(hDC);
memoryBitmap = CreateCompatibleBitmap(hDC, width, height);
SelectObject(memoryDC, memoryBitmap);
BitBlt(memoryDC, 0, 0, width, height, hDC, 0, 0, SRCCOPY);
ReleaseDC(hwnd, hDC);
}
//Copy memory windows content to real window at the screen
void RestoreWindow()
{
PAINTSTRUCT ps;
HDC hDC = BeginPaint(hwnd, &ps);
memoryDC = CreateCompatibleDC(hDC);
SelectObject(memoryDC, memoryBitmap);
BitBlt(hDC, 0, 0, width, height, memoryDC, 0, 0, SRCCOPY);
EndPaint(hwnd, &ps);
}
What I'm doing wrong?
UPD:
A shot in the dark: You're handling the middle button click. Are you by any chance clicking on the left or right mouse buttons? :)
Ok. Now I use WM_LBUTTONUP or WM_LBUTTONDOWN. Nothing happens again.
UPD2:
When you change the memory DC, you'll also want to invalidate the part of the window that is affected so that Windows will generate a WM_PAINT message for it. InvalidateRect would be a good place to start.
I placed this code
RECT rect;
GetClientRect(hwnd, &rect);
InvalidateRect(hwnd, &rect, true);
before EndPaint. Nothing. Than I move it after EndPaint. Nothing.
In the WM_PAINT handler, you need to use a DC provided by BeginPaint and call EndPaint when you're done with it.
I do it in RestoreWindow().
I don't know yet what's the problem...
UPD3:
InvalidateRect() needs to happen in the WM_?BUTTONDOWN handler after the SetPixel (not in RestoreWindow())- it's what tells windows that you want to get a WM_PAINT in the first place.
Ok. I've done it before you wrote this message. Still don't work.
UPD4:
Thank you a lot, Remy! Thank you to all the rest. Now all right!!
Two things.
When you change the memory DC, you'll also want to invalidate the part of the window that is affected so that Windows will generate a WM_PAINT message for it. InvalidateRect would be a good place to start.
In the WM_PAINT handler, you need to use a DC provided by BeginPaint and call EndPaint when you're done with it.
When you call RestoreWindow() to draw the bitmap onscreen, you are wiping out your memoryDC variable that you used to draw the pixels with. The bitmap is still selected into the original HDC that you have now lost, and a bitmap cannot be selected into multiple HDCs at the same time (the MSDN documentation for SelectObject() says as much). So you are not actually drawing the bitmap onscreen at all.
There is no need to call CreateCompatibleDC() or SelectObject() inside of RestoreWindow() because you already have the bitmap and memory HDC set up inside of StoreWindow(), so they use them as-is instead.
Try this:
HDC memoryDC = NULL;
HBITMAP memoryBitmap = NULL;
int width = 0, height = 0;
void CheckWidthHeight()
{
RECT clientRect;
GetClientRect(hwnd, &clientRect);
width = clientRect.right - clientRect.left;
height = clientRect.bottom - clientRect.top;
}
void StoreWindow()
{
HDC hDC = GetDC(hwnd);
memoryDC = CreateCompatibleDC(hDC);
memoryBitmap = CreateCompatibleBitmap(hDC, width, height);
SelectObject(memoryDC, memoryBitmap);
BitBlt(memoryDC, 0, 0, width, height, hDC, 0, 0, SRCCOPY);
ReleaseDC(hwnd, hDC);
}
void RestoreWindow()
{
PAINTSTRUCT ps;
HDC hDC = BeginPaint(hwnd, &ps);
if (memoryDC)
BitBlt(hDC, 0, 0, width, height, memoryDC, 0, 0, SRCCOPY);
EndPaint(hwnd, &ps);
}
...
case WM_SIZE:
{
CheckWidthHeight();
break;
}
case WM_LBUTTONDOWN:
{
if (!memoryDC)
StoreWindow();
if (memoryDC)
{
SetPixel(memoryDC, LOWORD(lParam), HIWORD(lParam), RGB(0,0,0));
RECT rect;
rect.left = LOWORD(lParam);
rect.top = HIWORD(lParam);
rect.right = rect.left + 1;
rect.bottom = rect.top + 1;
InvalidateRect(hwnd, &rect, TRUE);
}
break;
}
case WM_PAINT:
{
RestoreWindow();
break;
}
...