Make a win32 window transparent to messages (click, touch, keyboard) - winapi

I created a semi transparent window using the source code from this discussion (posted by wilkie):
How to make an OpenGL rendering context with transparent background?
It works, but I would like my window not to pick up mouse, touch and keyboard click messages.
But above all, I would like these messages (click, touch, keyboard) to be received by the application located below my transparent window.
Example:
My transparent window (TOP_MOST) is located on top of NotePad ++. If I click on my transparent window, I want this click to be received by NotePad++ and not by my transparent window.
I did not find valid answers on the Internet.
I see two possibilities:
_ Make my window transparent to all messages
_ Or my transparent window must receive the messages, not react and redirect them by sending them to the window located below.
In both cases, I don't know how to do it :)
Is it possible ?
Regards,
Edit with code:
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <windowsx.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <dwmapi.h>
#pragma comment (lib, "opengl32.lib")
#pragma comment (lib, "glu32.lib")
#pragma comment (lib, "dwmapi.lib")
#include <assert.h>
#include <tchar.h>
#ifdef assert
#define verify(expr) if(!expr) assert(0)
#else verify(expr) expr
#endif
const TCHAR szAppName[] = _T("TransparentGL");
const TCHAR wcWndName[] = _T("TransparentGL");
HDC hDC;
HGLRC m_hrc;
int w = 240;
int h = 240;
BOOL initSC() {
glEnable(GL_ALPHA_TEST);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0, 0, 0, 0);
return 0;
}
void resizeSC(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
BOOL renderSC() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glColor3f(0, 1, 1);
glBegin(GL_TRIANGLES); // Drawing Using Triangles
glColor3f(1.0f, 0.0f, 0.0f); // Set The Color To Red
glVertex3f(0.0f, 1.0f, 0.0f); // Top
glColor3f(0.0f, 1.0f, 0.0f); // Set The Color To Green
glVertex3f(-1.0f, -1.0f, 0.0f); // Bottom Left
glColor3f(0.0f, 0.0f, 1.0f); // Set The Color To Blue
glVertex3f(1.0f, -1.0f, 0.0f); // Bottom Right
glEnd();
glPopMatrix();
glFlush();
return 0;
}
BOOL CreateHGLRC(HWND hWnd) {
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_SUPPORT_COMPOSITION | // Format Must Support Composition
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
32, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
8, // An Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
24, // 16Bit Z-Buffer (Depth Buffer)
8, // Some Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
HDC hdc = GetDC(hWnd);
int PixelFormat = ChoosePixelFormat(hdc, &pfd);
if (PixelFormat == 0) {
assert(0);
return FALSE;
}
BOOL bResult = SetPixelFormat(hdc, PixelFormat, &pfd);
if (bResult == FALSE) {
assert(0);
return FALSE;
}
m_hrc = wglCreateContext(hdc);
if (!m_hrc) {
assert(0);
return FALSE;
}
ReleaseDC(hWnd, hdc);
return TRUE;
}
LRESULT CALLBACK WindowFunc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_CREATE:
break;
case WM_DESTROY:
if (m_hrc) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(m_hrc);
}
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hThisInst, HINSTANCE hPrevInst, LPSTR str, int nWinMode) {
WNDCLASSEX wc;
memset(&wc, 0, sizeof(wc));
wc.cbSize = sizeof(WNDCLASSEX);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)WindowFunc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hThisInst;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)CreateSolidBrush(0x00000000);
wc.lpszClassName = szAppName;
if (!RegisterClassEx(&wc)) {
MessageBox(NULL, _T("RegisterClassEx - failed"), _T("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
HWND hWnd = CreateWindowEx(WS_EX_APPWINDOW | WS_EX_TOPMOST | WS_EX_TRANSPARENT, szAppName, wcWndName,
WS_VISIBLE | WS_POPUP, 200, 150, w, h,
NULL, NULL, hThisInst, NULL);
if (!hWnd) {
MessageBox(NULL, _T("CreateWindowEx - failed"), _T("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
DWM_BLURBEHIND bb = { 0 };
HRGN hRgn = CreateRectRgn(0, 0, -1, -1);
bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
bb.hRgnBlur = hRgn;
bb.fEnable = TRUE;
DwmEnableBlurBehindWindow(hWnd, &bb);
CreateHGLRC(hWnd);
HDC hdc = GetDC(hWnd);
wglMakeCurrent(hdc, m_hrc);
initSC();
resizeSC(w, h);
ReleaseDC(hWnd, hdc);
MSG msg;
while (1) {
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else {
HDC hdc = GetDC(hWnd);
wglMakeCurrent(hdc, m_hrc);
renderSC();
SwapBuffers(hdc);
ReleaseDC(hWnd, hdc);
}
}
return (FALSE);
}

You can add the WS_EX_LAYERED style when creating the form, and set the opacity of the window through the SetLayeredWindowAttributes function.
HWND hWnd = CreateWindowEx(WS_EX_LAYERED | WS_EX_APPWINDOW | WS_EX_TOPMOST | WS_EX_TRANSPARENT, szAppName, wcWndName,
WS_VISIBLE | WS_POPUP, 200, 150, w, h,
NULL, NULL, hThisInst, NULL);
if (!hWnd) {
MessageBox(NULL, _T("CreateWindowEx - failed"), _T("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
SetLayeredWindowAttributes(hWnd, 0, 255, LWA_ALPHA);
Then it works for me:

Thanks to Zhu Song - MSFT and David Heffernan, this is the full source code of the modified sample originaly posted in this post:
How to make an OpenGL rendering context with transparent background?
It display an OpenGL Triangle in transparente Window and support Click-Through:
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <windowsx.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <dwmapi.h>
#pragma comment (lib, "opengl32.lib")
#pragma comment (lib, "glu32.lib")
#pragma comment (lib, "dwmapi.lib")
#include <assert.h>
#include <tchar.h>
#ifdef assert
#define verify(expr) if(!expr) assert(0)
#else verify(expr) expr
#endif
const TCHAR szAppName[] = _T("TransparentGL");
const TCHAR wcWndName[] = _T("TransparentGL");
HDC hDC;
HGLRC m_hrc;
int w = 240;
int h = 240;
BOOL initSC() {
glEnable(GL_ALPHA_TEST);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0, 0, 0, 0);
return 0;
}
void resizeSC(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
BOOL renderSC() {
static float angle = 0.0f;
angle = (angle < 360.0f ) ? angle + 0.01f : 0.0f;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(angle, 0.0f, 0.0f, 1.0f);
glColor3f(0, 1, 1);
glBegin(GL_TRIANGLES); // Drawing Using Triangles
glColor4f(1.0f, 0.0f, 0.0f,0.5f); // Set The Color To Red
glVertex3f(0.0f, 1.0f, 0.0f); // Top
glColor4f(0.0f, 1.0f, 0.0f, 0.5f); // Set The Color To Green
glVertex3f(-1.0f, -1.0f, 0.0f); // Bottom Left
glColor4f(0.0f, 0.0f, 1.0f, 0.5f); // Set The Color To Blue
glVertex3f(1.0f, -1.0f, 0.0f); // Bottom Right
glEnd();
glPopMatrix();
glFlush();
return 0;
}
BOOL CreateHGLRC(HWND hWnd) {
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_SUPPORT_COMPOSITION | // Format Must Support Composition
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
32, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
8, // An Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
24, // 16Bit Z-Buffer (Depth Buffer)
8, // Some Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
HDC hdc = GetDC(hWnd);
int PixelFormat = ChoosePixelFormat(hdc, &pfd);
if (PixelFormat == 0) {
assert(0);
return FALSE;
}
BOOL bResult = SetPixelFormat(hdc, PixelFormat, &pfd);
if (bResult == FALSE) {
assert(0);
return FALSE;
}
m_hrc = wglCreateContext(hdc);
if (!m_hrc) {
assert(0);
return FALSE;
}
ReleaseDC(hWnd, hdc);
return TRUE;
}
LRESULT CALLBACK WindowFunc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
PAINTSTRUCT ps;
switch (msg) {
case WM_CREATE:
break;
case WM_DESTROY:
if (m_hrc) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(m_hrc);
}
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hThisInst, HINSTANCE hPrevInst, LPSTR str, int nWinMode) {
WNDCLASSEX wc;
memset(&wc, 0, sizeof(wc));
wc.cbSize = sizeof(WNDCLASSEX);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)WindowFunc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hThisInst;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)CreateSolidBrush(0x00000000);
wc.lpszClassName = szAppName;
if (!RegisterClassEx(&wc)) {
MessageBox(NULL, _T("RegisterClassEx - failed"), _T("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
HWND hWnd = CreateWindowEx(WS_EX_LAYERED | WS_EX_APPWINDOW | WS_EX_TOPMOST | WS_EX_TRANSPARENT, szAppName, wcWndName,
WS_VISIBLE | WS_POPUP, 200, 150, w, h,
NULL, NULL, hThisInst, NULL);
if (!hWnd) {
MessageBox(NULL, _T("CreateWindowEx - failed"), _T("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
SetLayeredWindowAttributes(hWnd, 0, 255, LWA_ALPHA);
DWM_BLURBEHIND bb = { 0 };
HRGN hRgn = CreateRectRgn(0, 0, -1, -1);
bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
bb.hRgnBlur = hRgn;
bb.fEnable = TRUE;
DwmEnableBlurBehindWindow(hWnd, &bb);
CreateHGLRC(hWnd);
HDC hdc = GetDC(hWnd);
wglMakeCurrent(hdc, m_hrc);
initSC();
resizeSC(w, h);
ReleaseDC(hWnd, hdc);
MSG msg;
while (1) {
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else {
HDC hdc = GetDC(hWnd);
wglMakeCurrent(hdc, m_hrc);
renderSC();
SwapBuffers(hdc);
ReleaseDC(hWnd, hdc);
}
}
return (FALSE);
}
If it can help other peoples, if you want to do the same thing with QT:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
_glWidget = new MyOpenGLWidget(this); // derived from: public QOpenGLWidget, protected QOpenGLFunctions_3_3_Core
setAttribute(Qt::WA_InputMethodTransparent);
setAttribute(Qt::WA_TranslucentBackground, true);
setAttribute(Qt::WA_TransparentForMouseEvents);
SetForegroundWindow((HWND)winId());
setWindowFlags(Qt::Window | Qt::FramelessWindowHint |Qt::WindowStaysOnTopHint);
ui->verticalLayout->addWidget(_glWidget);
}

Related

C++ Transparent image using windows.h / WinAPI

I'm trying to make a custom title bar/border and I want it to be half transparent. When I load the image it works fine, but as soon, as I make even just 1 pixel from 255 opacity to 254, it just shows a white image.
Help would really be appreciated!
I use the windows.h library.
I use a resource ( .rc ) file to get the location of the images.
Don't think about where im doing things right, it's just for testing. I know it's not very efficient.
The Code!
( or at least the most of it / the important )
#include "../resource/resource.h"
#include "../header/Window.h"
#pragma warning(disable : 4244)
/////////////////////////
// Window
//
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
HWND m_hWnd;
POINT wndSize = { 900, 900 };
Window::Window() : m_hInstance(GetModuleHandle(nullptr))
{
const wchar_t * className = L"Main Window";
WNDCLASS wc = {};
wc.lpszClassName = className;
wc.hInstance = m_hInstance;
wc.hIcon = LoadIcon(m_hInstance, MAKEINTRESOURCE(IDI_ICON));
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpfnWndProc = WindowProc;
wc.hbrBackground = CreatePatternBrush(LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_BG)));
RegisterClass(&wc);
DWORD style = NULL;
RECT rect;
rect.left = GetSystemMetrics(SM_CXSCREEN) * .5 - (wndSize.x * .5);
rect.top = GetSystemMetrics(SM_CYSCREEN) * .5 - (wndSize.y * .5);
rect.right = rect.left + wndSize.x;
rect.bottom = rect.top + wndSize.y;
AdjustWindowRect(&rect, style, false);
m_hWnd = CreateWindowEx(
0,
className,
L"Chess",
style,
rect.left,
rect.top,
rect.right - rect.left,
rect.bottom - rect.top,
NULL,
NULL,
m_hInstance,
NULL
);
SetWindowLongPtr(m_hWnd, GWL_STYLE, NULL); // Remove the default borders
ShowWindow(m_hWnd, SW_SHOW);
}
Window::~Window()
{
const wchar_t * className = L"Main Window";
UnregisterClass(className, m_hInstance);
}
bool Window::ProcessMessage()
{
MSG msg = {};
RECT rectBorder;
HBRUSH colorBorder = CreatePatternBrush(LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TOP)));
//BitBlt(GetWindowDC(m_hWnd), 0, 0, 900, 30, GetWindowDC(m_hWnd), 0, 0, SRCINVERT);
//BitBlt(GetWindowDC(m_hWnd), 0, 0, 900, 30, GetWindowDC(m_hWnd), 0, 0, SRCAND);
//BitBlt(GetWindowDC(m_hWnd), 0, 0, 900, 30, GetWindowDC(m_hWnd), 0, 0, SRCINVERT);
while(PeekMessage(&msg, nullptr, 0u, 0u, PM_REMOVE))
{
switch(msg.message)
{
case WM_MOUSEMOVE: // On mouse motion
Window::updateWndEvents();
break;
case WM_PAINT: // On draw request
rectBorder = { 0, 0, wndSize.x, 30 };
FillRect(GetWindowDC(m_hWnd), &rectBorder, colorBorder); // Draw the top border
break;
case WM_QUIT: // On quit
return false;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return true;
}
/////////////////////////
// Window Functions
//
void Window::resizeWindow()
{
}
void Window::moveWindow()
{
}
void Window::updateWndEvents()
{
}
The alpha channel of a PNG image cannot be loaded using LoadBitmap.
It is recommended to use LockBits with PixelFormat32bppARGB in GDI+.

winapi How to draw opaque text on a transparent window background?

Using the Windows API, I'm trying to draw opaque text on a semi-transparent background. Using SetLayeredWindowAttributes(hWnd, RGB(0, 0, 0), 128, LWA_ALPHA); and a window style of WS_EX_LAYERED, I've managed to make the entire window semi-transparent, but that also includes the text.
How do I keep the text opaque and the background translucent?
In order to do "proper" alpha in a layered window you need to supply the window manager with a PARGB bitmap by a call to UpdateLayeredWindow.
Try the code below, it works for me.
#include <Windows.h>
#include <stdio.h>
#include <iostream>
#include <ObjIdl.h>
#include <gdiplus.h>
#include <gdiplusheaders.h>
using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")
#define MAX_WIDTH 800
#define MAX_HEIGHT 600
using namespace std;
void Drawtext(HWND hwnd, HDC hdc);
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == WM_DESTROY) {
PostQuitMessage(0);
}
return DefWindowProc(hwnd, message, wParam, lParam);
};
HINSTANCE hinst;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevinstance, PSTR szCmdLine, int iCmdShow) {
HWND hWnd;
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
//Initialize GDI+
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
hinst = GetModuleHandle(NULL);
// create a window class:
WNDCLASS wc = {};
wc.lpfnWndProc = WndProc;
wc.hInstance = hinst;
wc.lpszClassName = L"win32";
// register class with operating system:
RegisterClass(&wc);
// create and show window:
hWnd = CreateWindowExW(
WS_EX_LAYERED | WS_EX_TOPMOST,
L"win32",
L"WinSoup",
WS_POPUP,
0, 0, 1000, 500,
nullptr,
nullptr,
hInstance,
nullptr
);
if (hWnd == NULL) {
return 0;
}
Drawtext(hWnd, GetDC(hWnd));
ShowWindow(hWnd, SW_SHOW);
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
void Drawtext(HWND hwnd, HDC hdc)
{
FontFamily fontFamily(L"Times New Roman");
Font font(&fontFamily, 32, FontStyleRegular, UnitPixel);
PointF pointF(30.0f, 10.0f);
SolidBrush solidBrush(Color(255, 0, 0, 0));
Bitmap softwareBitmap(MAX_WIDTH, MAX_HEIGHT, PixelFormat32bppARGB);
Graphics g(&softwareBitmap);
g.Clear(Gdiplus::Color(30, 0, 0, 0)); // 30: alpha value
g.DrawString(L"Hello Hello Hello Hello Hello Hello Hello Hello", -1, &font, pointF, &solidBrush);
HBITMAP bmp;
softwareBitmap.GetHBITMAP(Color(0, 0, 0, 0), &bmp);
HDC memdc = CreateCompatibleDC(hdc);
HGDIOBJ original = SelectObject(memdc, bmp);
BLENDFUNCTION blend = { 0 };
blend.BlendOp = AC_SRC_OVER;
blend.SourceConstantAlpha = 255;
blend.AlphaFormat = AC_SRC_ALPHA;
POINT ptLocation = { 200, 300 };
SIZE szWnd = { MAX_WIDTH, MAX_HEIGHT };
POINT ptSrc = { 0, 0 };
UpdateLayeredWindow(hwnd, hdc, &ptLocation, &szWnd, memdc, &ptSrc, 0, &blend, ULW_ALPHA);
SelectObject(hdc, original);
DeleteObject(bmp);
DeleteObject(memdc);
}
Debug:
For more details, you can refer to #Koro's answer.

Windows XP repaints OpenGL application without any messages

I'm using Windows XP with a pretty old Intel video adapter (82945G). It supports OpenGL 1.1.
There is a simple OpenGL application. It processes WM_PAINT message and draws the scene.
The problem is that when I press the Start button the window gets completely erased. Some rubbish appears there. The same situation is happening when I hover cursor on close button and a tooltip appears.
I have checked that the application receives no messages during that.
Something makes me think that windows just repaints desktop and erases my window. How could I avoid that?
Run the application. Make sure that window is on the desktop. Resize it a bit. the press start button or hover cursor over close button and waint until tooltip appear.
Here is a source code:
#include <stdio.h>
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>
HDC hDC=NULL;
HGLRC hRC=NULL;
HWND hWnd=NULL;
HINSTANCE hInstance;
bool keys[256];
bool active=TRUE;
bool fullscreen=TRUE;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
GLvoid ReSizeGLScene(GLsizei width, GLsizei height)
{
if (height==0)height=1;
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int InitGL(GLvoid)
{
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
return TRUE;
}
int DrawGLScene(GLvoid)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
return TRUE;
}
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
GLuint PixelFormat;
WNDCLASS wc;
DWORD dwExStyle;
DWORD dwStyle;
RECT WindowRect;
WindowRect.left=(long)0;
WindowRect.right=(long)width;
WindowRect.top=(long)0;
WindowRect.bottom=(long)height;
fullscreen=fullscreenflag;
hInstance = GetModuleHandle(NULL);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = "OpenGL";
if (!RegisterClass(&wc))
{
MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE;
}
dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwStyle=WS_OVERLAPPEDWINDOW;
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
// Create The Window
if (!(hWnd=CreateWindowEx( dwExStyle,"OpenGL", title,dwStyle |
WS_CLIPSIBLINGS |WS_CLIPCHILDREN,0, 0,WindowRect.right-WindowRect.left,
WindowRect.bottom-
WindowRect.top,NULL,NULL,hInstance,NULL)))return FALSE;
static PIXELFORMATDESCRIPTOR pfd=
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
bits,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
16,
0,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
if (!(hDC=GetDC(hWnd))) return FALSE;
if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) return FALSE;
if(!SetPixelFormat(hDC,PixelFormat,&pfd))return FALSE;
if (!(hRC=wglCreateContext(hDC)))return FALSE;
if(!wglMakeCurrent(hDC,hRC))return FALSE;
ShowWindow(hWnd,SW_SHOW);
SetForegroundWindow(hWnd);
SetFocus(hWnd);
ReSizeGLScene(width, height);
if (!InitGL())return FALSE;
return TRUE;
}
LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
wchar_t buffer[256];
swprintf(buffer,L"message is: %d\n");
OutputDebugStringW(buffer);
switch (uMsg)
{
case WM_SIZE:
{
ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));
return 0;
}
case WM_PAINT:
{
DrawGLScene();
SwapBuffers(hDC);
RECT rect;
GetClientRect(hWnd,&rect);
ValidateRect(hWnd,&rect);
return 0;
}
}
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
BOOL done=FALSE;
fullscreen=FALSE;
CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen);
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}

How do I fix my resize function

This is all the code I have. The functions begining with zx are just so that when I'm done I can quickly put together a custom library based on those functions. The function I need help with is zxResizeGL which is used only on the WM_SIZE event atm.
#include <windows.h>
#include <gl/gl.h>
LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);
void EnableOpenGL(HWND hwnd, HDC*, HGLRC*);
void DisableOpenGL(HWND, HDC, HGLRC);
/* Necessary value we need access to */
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#define ZX_THIS_INSTANCE ((HINSTANCE)&__ImageBase)
/* We define 2 here so dev can retrieve the FPN b4 it is multiplied by 100 */
#define ZX__PERCENT( NUM, OF ) ( ( NUM ) / ( OF ) )
#define ZX_PERCENT( NUM, OF ) ( ZX__PERCENT( NUM, OF ) * 100 )
WNDCLASSEX zxGetOSWindowClassEX( void );
BOOL zxInitOSClasses( void );
HWND zxNewOSWindow( int w, int h, int x, int y, char const *text );
HDC hDC = NULL;
HGLRC hRC = NULL;
void zxResizeGL(int width, int height )
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, -1.0, 1.0);
glFlush();
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
HWND hwnd;
MSG msg;
BOOL bQuit = FALSE;
float theta = 0,
width = 256,
height = width,
w = ZX__PERCENT( width - 20, width ),
h = w;
if ( !zxInitOSClasses() )
return 0;
hwnd = zxNewOSWindow( 480, 480, 0, 0, "OpenGL Sample" );
ShowWindow(hwnd, nCmdShow);
/* enable OpenGL for the window */
EnableOpenGL(hwnd, &hDC, &hRC);
/* program main loop */
while (!bQuit)
{
/* check for messages */
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
/* handle or dispatch messages */
switch ( msg.message )
{
case WM_QUIT:
bQuit = TRUE;
break;
case WM_SIZE:
/* This is where I'm trying to peform the resize */
width = LOWORD( msg.lParam );
height = HIWORD( msg.lParam );
w = ZX__PERCENT( width - 20, width );
h = ZX__PERCENT( height - 20, height );
zxResizeGL( width, height );
break;
default:
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
/* OpenGL animation code goes here */
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glRotatef(theta, 0.0f, 0.0f, 1.0f);
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f); glVertex2f( 0.0f, h );
glColor3f(0.0f, 1.0f, 0.0f); glVertex2f( w, -h );
glColor3f(0.0f, 0.0f, 1.0f); glVertex2f( -w, -h );
glEnd();
glPopMatrix();
SwapBuffers(hDC);
theta += 1.0f;
Sleep (1);
}
}
/* shutdown OpenGL */
DisableOpenGL(hwnd, hDC, hRC);
/* destroy the window explicitly */
DestroyWindow(hwnd);
return msg.wParam;
}
The defines for the functions broken off from main code.
WNDCLASSEX zxGetOSWindowClassEX( void )
{
WNDCLASSEX wx = {0};
wx.cbSize = sizeof( WNDCLASSEX );
wx.style = CS_OWNDC;
wx.lpfnWndProc = WindowProc;
wx.hInstance = ZX_THIS_INSTANCE;
wx.hIcon = LoadIcon( NULL, IDI_APPLICATION );
wx.hCursor = LoadCursor( NULL, IDC_ARROW );
wx.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wx.lpszClassName = "zxOSWindow";
wx.hIconSm = LoadIcon( NULL, IDI_APPLICATION );
return wx;
}
BOOL zxInitOSClasses( void )
{
WNDCLASSEX wx = zxGetOSWindowClassEX();
if ( !RegisterClassEx( &wx ) )
return 0;
return 1;
}
HWND zxNewOSWindow( int w, int h, int x, int y, char const *text )
{
WNDCLASSEX wx = zxGetOSWindowClassEX();
return CreateWindowEx(
0, wx.lpszClassName, text,
WS_OVERLAPPEDWINDOW,
x, y, w, h, NULL, NULL,
wx.hInstance, NULL );
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_DESTROY:
return 0;
case WM_KEYDOWN:
{
switch (wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
break;
}
}
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC)
{
PIXELFORMATDESCRIPTOR pfd;
int iFormat;
/* get the device context (DC) */
*hDC = GetDC(hwnd);
/* set the pixel format for the DC */
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
iFormat = ChoosePixelFormat(*hDC, &pfd);
SetPixelFormat(*hDC, iFormat, &pfd);
/* create and enable the render context (RC) */
*hRC = wglCreateContext(*hDC);
wglMakeCurrent(*hDC, *hRC);
}
void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC)
{
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hRC);
ReleaseDC(hwnd, hDC);
}
Microsoft says WM_SIZE messages are sent (not posted) and thus come in via WindowProc().
PeekMessage() can only retrieve posted messages.
Handle WM_SIZE in your WindowProc().
After having tried a break point I noticed I was not receiving the WM_SIZE event, will investigate alternate ways to perform resize. For now I will put the zxResizeGL in the drawing loop

Cairo linear gradient with Win32 double buffering

I'm trying to make Cairo work in a Win32 window. The idea is just to make it render flicker-free.
If I create a Cairo surface directly with the window's HDC, then the window will flicker on resizing. That's normal, and expected. The usual solution is to create a compatible device context and render to a bitmap, then blit that bitmap to the window HDC.
The problem is that the same drawing code that worked when using the window's HDC doesn't work on the double-buffer device context. I just get a black square rather than a gradient circle.
Here's a small, functional example. If you comment out the #define DOUBLE_BUFFER line, then it will draw the Cairo rendering directly to the window's HDC. Otherwise, it will draw to the created one.
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include <cairo.h>
#include <cairo-win32.h>
// Global variables
// The main window class name.
static TCHAR szWindowClass[] = _T("CairoTestApp");
// The string that appears in the application's title bar.
static TCHAR szTitle[] = _T("Cairo Test Application");
HINSTANCE hInst;
// Forward declarations of functions included in this code module:
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int main(int argc, const char *argv)
{
HINSTANCE hInstance = GetModuleHandle(NULL);
WNDCLASSEX 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_APPLICATION));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
if (!RegisterClassEx(&wcex))
{
MessageBox(NULL, _T("Call to RegisterClassEx failed!"), szTitle, NULL);
return 1;
}
hInst = hInstance; // Store instance handle in our global variable
// The parameters to CreateWindow explained:
// szWindowClass: the name of the application
// szTitle: the text that appears in the title bar
// WS_OVERLAPPEDWINDOW: the type of window to create
// CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
// 500, 100: initial size (width, length)
// NULL: the parent of this window
// NULL: this application does not have a menu bar
// hInstance: the first parameter from WinMain
// NULL: not used in this application
HWND hWnd = CreateWindow(
szWindowClass,
szTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
256, 256,
NULL,
NULL,
hInstance,
NULL
);
if (!hWnd)
{
MessageBox(NULL, _T("Call to CreateWindow failed!"), szTitle, NULL);
return 1;
}
// The parameters to ShowWindow explained:
// hWnd: the value returned from CreateWindow
// nCmdShow: the fourth parameter from WinMain
ShowWindow(hWnd, SW_SHOWNORMAL);
UpdateWindow(hWnd);
// Main message loop:
MSG msg;
while(true)
{
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
// DestroyWindow(hWnd);
UnregisterClass(szWindowClass, hInstance);
return 0;
}
void gradientExample( cairo_t* cr ) {
cairo_pattern_t *pat;
pat = cairo_pattern_create_linear (0.0, 0.0, 0.0, 256.0);
cairo_pattern_add_color_stop_rgba (pat, 1, 0, 0, 0, 1);
cairo_pattern_add_color_stop_rgba (pat, 0, 1, 1, 1, 1);
cairo_rectangle (cr, 0, 0, 256, 256);
cairo_set_source (cr, pat);
cairo_fill (cr);
cairo_pattern_destroy (pat);
pat = cairo_pattern_create_radial (115.2, 102.4, 25.6,
102.4, 102.4, 128.0);
cairo_pattern_add_color_stop_rgba (pat, 0, 1, 1, 1, 1);
cairo_pattern_add_color_stop_rgba (pat, 1, 0, 0, 0, 1);
cairo_set_source (cr, pat);
cairo_arc (cr, 128.0, 128.0, 76.8, 0, 2 * 3.14159);
cairo_fill (cr);
cairo_pattern_destroy (pat);
}
#define DOUBLE_BUFFER
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
TCHAR greeting[] = _T("Hello, World!");
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
{
HDC newDC = CreateCompatibleDC(hdc);
RECT theRect;
GetClientRect(hWnd, &theRect);
int width, height;
width = theRect.right - theRect.left;
height = theRect.bottom - theRect.top;
HBITMAP theBmp = CreateCompatibleBitmap(newDC, width, height);
HGDIOBJ oldBmp = SelectObject(newDC, theBmp);
//Test some text.
#ifdef DOUBLE_BUFFER
TextOut(newDC, 5, 5, greeting, _tcslen(greeting));
#else
TextOut(hdc, 5, 5, greeting, _tcslen(greeting));
#endif
{
#ifdef DOUBLE_BUFFER
cairo_surface_t *surface = cairo_win32_surface_create(newDC);
#else
cairo_surface_t *surface = cairo_win32_surface_create(hdc);
#endif
cairo_t *cr = cairo_create(surface);
// Draw on the cairo context.
cairo_set_source_rgb(cr, 1, 1, 1);
cairo_paint(cr);
gradientExample( cr );
cairo_surface_finish(surface);
// Cleanup.
cairo_destroy(cr);
cairo_surface_destroy(surface);
}
#ifdef DOUBLE_BUFFER
BitBlt(hdc, 0, 0, width, height, newDC, theRect.left, theRect.top, SRCCOPY);
#endif
SelectObject(newDC, oldBmp);
DeleteDC(newDC);
}
EndPaint(hWnd, &ps);
break;
case WM_ERASEBKGND:
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_KEYDOWN: // Is A Key Being Held Down?
{
if(wParam == VK_ESCAPE)
{
PostMessage(hWnd, WM_CLOSE, 0, 0);
}
}
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
break;
}
return 0;
}
Try calling CreateCompatibleBitmap with the original device context (hdc) as parameter instead. Otherwise I believe you'll get one based on the default monochrome dummy bitmap of the supposedly-compatible DC you just created.

Resources