|
|
|
How to create a window with custom shape (making some parts transparent)In this article, I'll show you how to create a window with any arbitrary shape you like. How we are going to do is very simple. We just draw a bitmap using paint or other tool, with the shape we need our window to be. We give a special color for the regions which we want to make transparent. Then, we create a region (CRgn) using this bitmap, only including the pixels in the bitmap which is not that special color. Then simply we call SetWindowRgn() to set the region of our window to the region we created. Here is the bitmap i used (scaled down). I created it using MS Paint.
And here is the window i get.
Now it should be clear. Now, lets go coding. First, create a dialog based C++ MFC application in Visual Studio. Create the bitmap with the shape you want your window to be. Use a special color to regions which should be transparent. Then, add that bitmap to the Visual Studio project as a resource. In example project, the resource name used is IDB_BITMAP1, which is the default. We have to set the window region before it is displayed. We add the code to set the region in the handler of WM_SIZE window message. To add that handler, you can go to the properties of the MFC dialog and select WM_SIZE from Message section.
Here is the function. void CtransparentwindowDlg::OnSize(UINT nType, int cx, int cy) The task of this function is load our bitmap into a memory device context and read pixel by pixel to see whether the color or the pixel is our special color. We have selected RGB(255, 0, 255) as our transparent color and created the bitmap according to that. The algorithm inside the for loop checks each and every pixel in the bitmap and finally creates a region which includes only the places not having the transparent color. Then, we simply call the function SetWindowRgn() to set the region we created as the window region. So, that's it. You can download the example project here. If this article and FrostCode is useful for you, please email us. |