SDL2 can't get mouse input when key is depressed - sdl-2

My SDL2 program ignores the mouse click if a key is depressed. Here's my MCVE:
#include <SDL.h>
void myEventHandler(bool& mouseClicked, bool& letsQuit)
{
SDL_Event event;
while (SDL_PollEvent(&event))
switch (event.type)
{
case SDL_QUIT: letsQuit = true; break;
case SDL_MOUSEBUTTONDOWN: mouseClicked = true;
}
}
int main(int argc, char** argv)
{
//Init SDL
SDL_Window* sldWindow;
SDL_Renderer* sdlRenderer;
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
return -1;
if (!(sldWindow = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,640, 480, 0)))
return -1;
if (!(sdlRenderer = SDL_CreateRenderer(sldWindow, -1, 0)))
return -1;
SDL_ClearError();
//Initialize some conditions
bool letsDrawRed= true; //Draw a red square, not blue
bool letsQuit = false; //Quit the program
while (! letsQuit)
{
SDL_RenderPresent(sdlRenderer);
//static int framesSinceLastMouseClick = 0; //latency
bool mouseClicked = false;
myEventHandler (mouseClicked, letsQuit);
if (letsDrawRed) SDL_SetRenderDrawColor(sdlRenderer, 255, 0, 0, 255); //draw square as red
else SDL_SetRenderDrawColor(sdlRenderer, 0, 0, 255, 255); //else draw it blue
static SDL_Rect rect = { 0, 0, 100, 100 }; //draw the square
SDL_RenderFillRect(sdlRenderer, &rect);
//if clicked, and enough time since last click...
//(All of these commented-out conditions fail too)
//if (framesSinceLastMouseClick > 600 && mouseClicked)
//if (framesSinceLastMouseClick > 600 && SDL_GetMouseState(NULL, NULL))
//if (mouseClicked)
if (SDL_GetMouseState(NULL,NULL))
{
//framesSinceLastMouseClick = 0;
letsDrawRed = !letsDrawRed;
}
//else ++framesSinceLastMouseClick;
}
SDL_DestroyWindow(sldWindow);
SDL_Quit();
return 0;
}
I left some things in comments to show they aren't the problem. One is the latency condition (framesSinceLastMouseClick). The other is getting the mouse event from SDL_PollEvent rather than calling SDL_GetMouseState.)
Another thing to note is this is only a problem when the key depressed is printable. CapsLock, Shift, Alt, Ctrl, and Function keys don't cause a problem.
Platform is Visual Studio on MS Windows.
So...how can I get to that mouse while a key is depressed? That's going to be a problem in a real game!

This turned out not to be SDL but the computer I'm on, which can't send info from the mouse (trackpad, actually) while a printable character is being pressed. Apparently sending multiple signals from the keyboard is a longstanding problem, and "keyboard ghosting" (some keys -- in my case, trackpad clicks -- being lost) is a result.
At time of posting, I was able to check what output my keyboard/trackpad can send at https://keyboardtester.co/mouse-click-tester.html.

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.

SDL2 Window turns black on resize

I have started to work with SDL2 and am not experienced with it. I am working on a Mac system. Almost everything has been good, but I have a problem that when a resizeable window is resized, while the handle is being dragged, the window turns black, and I can only repaint it after releasing. And I have checked that while the window is being resized, no event is being produced and I have no means to interfere or detect this, as the event loop is just paused. Is there any possible solutions?
Here is the code (Almost replica of a tutorial on handling resize event):
SDL_Event event;
SDL_Rect nativeSize;
SDL_Rect newWindowSize;
float scaleRatioW;//This is to change anything that might rely on something like mouse coords
float scaleRatioH; //(such as a button on screen) over to the new coordinate system scaling would create
SDL_Window * window; //Our beautiful window
SDL_Renderer * renderer; //The renderer for our window
SDL_Texture * backBuffer; //The back buffer that we will be rendering everything to before scaling up
SDL_Texture * ballImage; //A nice picture to demonstrate the scaling;
bool resize;
void InitValues(); //Initialize all the variables needed
void InitSDL(); //Initialize the window, renderer, backBuffer, and image;
bool HandleEvents(); //Handle the window changed size event
void Render(); //Switches the render target back to the window and renders the back buffer, then switches back.
void Resize(); //The important part for stretching. Changes the viewPort, changes the scale ratios
void InitValues()
{
nativeSize.x = 0;
nativeSize.y = 0;
nativeSize.w = 256;
nativeSize.h = 224; //A GameBoy size window width and height
scaleRatioW = 1.0f;
scaleRatioH = 1.0f;
newWindowSize.x = 0;
newWindowSize.y = 0;
newWindowSize.w = nativeSize.w;
newWindowSize.h = nativeSize.h;
window = NULL;
renderer = NULL;
backBuffer = NULL;
ballImage = NULL;
resize = false;
}
void InitSDL()
{
if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
//cout << "Failed to initialize SDL" << endl;
printf("%d\r\n", __LINE__);
}
//Set the scaling quality to nearest-pixel
if(SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0") < 0)
{
//cout << "Failed to set Render Scale Quality" << endl;
printf("%d\r\n", __LINE__);
}
//Window needs to be resizable
window = SDL_CreateWindow("Rescaling Windows!",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
256,
224,
SDL_WINDOW_RESIZABLE);
//You must use the SDL_RENDERER_TARGETTEXTURE flag in order to target the backbuffer
renderer = SDL_CreateRenderer(window,
-1,
SDL_RENDERER_ACCELERATED |
SDL_RENDERER_TARGETTEXTURE);
//Set to blue so it's noticeable if it doesn't do right.
SDL_SetRenderDrawColor(renderer, 0, 0, 200, 255);
//Similarly, you must use SDL_TEXTUREACCESS_TARGET when you create the texture
backBuffer = SDL_CreateTexture(renderer,
SDL_GetWindowPixelFormat(window),
SDL_TEXTUREACCESS_TARGET,
nativeSize.w,
nativeSize.h);
//IMPORTANT Set the back buffer as the target
SDL_SetRenderTarget(renderer, backBuffer);
//Load an image yay
SDL_Surface * image = SDL_LoadBMP("Ball.bmp");
ballImage = SDL_CreateTextureFromSurface(renderer, image);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_FreeSurface(image);
}
bool HandleEvents()
{
while(SDL_PollEvent(&event) )
{
printf("%d\r\n", __LINE__);
if(event.type == SDL_QUIT)
{
printf("%d\r\n", __LINE__);
return true;
}
else if(event.type == SDL_WINDOWEVENT)
{
if(event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
{
resize = true;
printf("%d\r\n", __LINE__);
}
}
return false;
}
return false;
}
void Render()
{
SDL_RenderCopy(renderer, ballImage, NULL, NULL); //Render the entire ballImage to the backBuffer at (0, 0)
printf("%d\r\n", __LINE__);
SDL_SetRenderTarget(renderer, NULL); //Set the target back to the window
if(resize)
{
Resize();
resize = false;
}
printf("%d\r\n", __LINE__);
SDL_RenderCopy(renderer, backBuffer, &nativeSize, &newWindowSize); //Render the backBuffer onto the screen at (0,0)
SDL_RenderPresent(renderer);
SDL_RenderClear(renderer); //Clear the window buffer
SDL_SetRenderTarget(renderer, backBuffer); //Set the target back to the back buffer
SDL_RenderClear(renderer); //Clear the back buffer
printf("%d\r\n", __LINE__);
}
void Resize()
{
int w, h;
printf("%d\r\n", __LINE__);
SDL_GetWindowSize(window, &w, &h);
scaleRatioW = w / nativeSize.w;
scaleRatioH = h / nativeSize.h; //The ratio from the native size to the new size
newWindowSize.w = w;
newWindowSize.h = h;
//In order to do a resize, you must destroy the back buffer. Try without it, it doesn't work
SDL_DestroyTexture(backBuffer);
backBuffer = SDL_CreateTexture(renderer,
SDL_GetWindowPixelFormat(window),
SDL_TEXTUREACCESS_TARGET, //Again, must be created using this
nativeSize.w,
nativeSize.h);
SDL_Rect viewPort;
SDL_RenderGetViewport(renderer, &viewPort);
if(viewPort.w != newWindowSize.w || viewPort.h != newWindowSize.h)
{
//VERY IMPORTANT - Change the viewport over to the new size. It doesn't do this for you.
SDL_RenderSetViewport(renderer, &newWindowSize);
}
}
int main(int argc, char * argv[])
{
InitValues();
InitSDL();
bool quit = false;
printf("%d\r\n", __LINE__);
while(!quit)
{
printf("%d\r\n", __LINE__);
quit = HandleEvents();
Render();
}
return 0;
}
Ok, after fighting a bit with SDL2, I got it working with macOS 10.12.
Here is the problem:
SDL2 catches resize events and resends only the last 3 when you poll events using SDL_PollEvent(&event) for example.
During this time (you pressed left mouse click on resize area and hold the mouse) the SDL_PollEvent is blocking.
Here is the workaround:
Luckily, you can hook into the event handler using SDL_SetEventFilter. This will fire every time a event is being received. So for all resize events as they occur.
So what you can do is to register your own event filter callback that basically allows every event (by returning 1), listens on resize events, and sends them to your draw loop.
Example:
//register this somewhere
int filterEvent(void *userdata, SDL_Event * event) {
if (event->type == SDL_WINDOWEVENT && event->window.event == SDL_WINDOWEVENT_RESIZED) {
//convert userdata pointer to yours and trigger your own draw function
//this is called very often now
//IMPORTANT: Might be called from a different thread, see SDL_SetEventFilter docs
((MyApplicationClass *)userdata)->myDrawFunction();
//return 0 if you don't want to handle this event twice
return 0;
}
//important to allow all events, or your SDL_PollEvent doesn't get any event
return 1;
}
///after SDL_Init
SDL_SetEventFilter(filterEvent, this) //this is instance of MyApplicationClass for example
Important: Do not call SDL_PollEvent within your filterEvent callback, as this will result in weird behaviour of stuck events. (resize will not stop sometimes for example)
Turns out that this is not specific to my code, and it is a part of a wider problem with all the OpenGL libraries in MacOSX. Although recent patches in GLFW has fixed it, and in the GLUT version which is provided with XCode itself, it is quite better and you just observe a flicker in the window while resizing.
https://github.com/openframeworks/openFrameworks/issues/2800
https://github.com/openframeworks/openFrameworks/issues/2456
The problem is because of the blocking nature of the OSX window manager, which blocks all the events until the mouse is released.
To solve this, you should manipulate the library you are using and recompile it. You should add these or something similar (depending on your development environment) to the resize handler to bypass the block:
ofNotifyUpdate();
instance->display();
which is disastrous, if you are a novice, and want the ability to use library updates without much difficulty. Another solution is to override the SDL behaviour, by writing another event handler that does that. It is better as it doesn't need editing the SDL code, but adds a pile of platform specific code that I personally don't tend to and would cause a lot of problems that I don't want to spend time fixing.
After 2 days of searching, because I had just started the project and not implemented much relying on SDL, I decided to switch to GLFW which has the smoothest resize handling and I observe no flicker.

change color of specific label win32

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;
}

Win32 opengl Window creation

What is the best way to set up a window in win32 that has OpenGl(and glsl if the needs extra code to work) integrated into it?
I have done some research and found numerous ways of accomplishing this task i was wondering what the best way is or what way you like the most if the best way doesn't have an answer.
I have looked at nehe`s design and also the one supplied by the OpenGl super bible which both have completely different ways of accomplishing it (also the super bibles one gives me errors :().
any help would be appreciated including tutorials etc.
thanks
All your "different ways" aren't so different. You have to:
create your window (in the usual Win32 way, with RegisterClass(Ex) and CreateWindow(Ex))
create a GDI device context corresponding to your window (GetDC)
pick a pixel format which is supported by the display (optional DescribePixelFormat, then ChoosePixelFormat)
create your OpenGL context (wglCreateContext)
(optional, but required to use GLSL) link OpenGL extension functions (GLee or GLEW helpers, or glGetString(GL_EXTENSIONS) then wglGetProcAddress)
(optional) create an OpenGL 3.x context, free the compatibility context (wglCreateContextAttribs)
make the context active (wglMakeCurrent)
start using OpenGL (set up shader programs, load textures, draw stuff, etc.)
An excerpt of code showing these steps in action (not suitable for copy+paste, a bunch of RAII wrappers are used):
bool Context::attach( HWND hwnd )
{
PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd), 1 };
if (!m_dc) {
scoped_window_hdc(hwnd).swap(m_dc);
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_SUPPORT_COMPOSITION | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cAlphaBits = 8;
pfd.iLayerType = PFD_MAIN_PLANE;
auto format_index = ::ChoosePixelFormat(m_dc.get(), &pfd);
if (!format_index)
return false;
if (!::SetPixelFormat(m_dc.get(), format_index, &pfd))
return false;
}
auto active_format_index = ::GetPixelFormat(m_dc.get());
if (!active_format_index)
return false;
if (!::DescribePixelFormat(m_dc.get(), active_format_index, sizeof pfd, &pfd))
return false;
if ((pfd.dwFlags & PFD_SUPPORT_OPENGL) != PFD_SUPPORT_OPENGL)
return false;
m_render_thread = ::CreateThread(NULL, 0, &RenderThreadProc, this, 0, NULL);
return m_render_thread != NULL;
}
DWORD WINAPI Context::RenderThreadProc( LPVOID param )
{
Context* const ctx = static_cast<Context*>(param);
HDC dc = ctx->m_dc.get();
SIZE canvas_size;
ctx->m_dc.check_resize(&canvas_size);
scoped_hglrc glrc(wglCreateContext(dc));
if (!glrc)
return EXIT_FAILURE;
if (!glrc.make_current(dc))
return EXIT_FAILURE;
if (ctx->m_major_version > 2 && GLEE_WGL_ARB_create_context) {
int const create_attribs[] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, ctx->m_major_version,
WGL_CONTEXT_MINOR_VERSION_ARB, ctx->m_minor_version,
0
};
scoped_hglrc advrc(wglCreateContextAttribsARB(dc, 0, create_attribs));
if (advrc) {
if (!advrc.make_current(dc))
return EXIT_FAILURE;
advrc.swap(glrc);
}
}
{
const char* ver = reinterpret_cast<const char*>(glGetString(GL_VERSION));
if (ver) {
OutputDebugStringA("GL_VERSION = \"");
OutputDebugStringA(ver);
OutputDebugStringA("\"\n");
}
}
glDisable(GL_DITHER);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.f, 0.f, 0.f, 1.f);
if (GLEE_WGL_EXT_swap_control)
wglSwapIntervalEXT(1);
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
while (!::InterlockedExchange(&ctx->m_stop_render, 0)) {
ctx->process_queued_tasks();
if (ctx->m_dc.check_resize(&canvas_size)) {
glViewport(0, 0, canvas_size.cx, canvas_size.cy);
ctx->process_on_resize();
}
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(vao);
ctx->process_on_render();
BOOL swapped = ::SwapBuffers(dc);
if (!swapped)
std::cout << "::SwapBuffers failure, GetLastError() returns " << std::hex << ::GetLastError() << std::endl;
}
ctx->m_program_db.clear();
return EXIT_SUCCESS;
}
It also doesn't cover window creation, it enables OpenGL on an existing window.
This pretty much did it for me: http://nehe.gamedev.net/tutorial/creating_an_opengl_window_%28win32%29/13001/
EDIT: Related code:
/*
* This Code Was Created By Jeff Molofee 2000
* A HUGE Thanks To Fredric Echols For Cleaning Up
* And Optimizing This Code, Making It More Flexible!
* If You've Found This Code Useful, Please Let Me Know.
* Visit My Site At nehe.gamedev.net
*/
#include <windows.h> // Header File For Windows
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include <gl\glaux.h> // Header File For The Glaux Library
HDC hDC=NULL; // Private GDI Device Context
HGLRC hRC=NULL; // Permanent Rendering Context
HWND hWnd=NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application
bool keys[256]; // Array Used For The Keyboard Routine
bool active=TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen=TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc
GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height==0) // Prevent A Divide By Zero By
{
height=1; // Making Height Equal One
}
glViewport(0,0,width,height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
}
int InitGL(GLvoid) // All Setup For OpenGL Goes Here
{
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
return TRUE; // Initialization Went OK
}
int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
return TRUE; // Everything Went OK
}
GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}
if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}
if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}
hRC=NULL; // Set RC To NULL
}
if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC
{
MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hDC=NULL; // Set DC To NULL
}
if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hWnd=NULL; // Set hWnd To NULL
}
if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class
{
MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hInstance=NULL; // Set hInstance To NULL
}
}
/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left=(long)0; // Set Left Value To 0
WindowRect.right=(long)width; // Set Right Value To Requested Width
WindowRect.top=(long)0; // Set Top Value To 0
WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height
fullscreen=fullscreenflag; // Set The Global Fullscreen Flag
hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = "OpenGL"; // Set The Class Name
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
return FALSE; // Return FALSE
}
}
}
if (fullscreen) // Are We Still In Fullscreen Mode?
{
dwExStyle=WS_EX_APPWINDOW; // Window Extended Style
dwStyle=WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style
}
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
// Create The Window
if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window
"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
0, 0, // Window Position
WindowRect.right-WindowRect.left, // Calculate Window Width
WindowRect.bottom-WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
ShowWindow(hWnd,SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen
if (!InitGL()) // Initialize Our Newly Created GL Window
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
return TRUE; // Success
}
LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active=TRUE; // Program Is Active
}
else
{
active=FALSE; // Program Is No Longer Active
}
return 0; // Return To The Message Loop
}
case WM_SYSCOMMAND: // Intercept System Commands
{
switch (wParam) // Check System Calls
{
case SC_SCREENSAVE: // Screensaver Trying To Start?
case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
return 0; // Prevent From Happening
}
break; // Exit
}
case WM_CLOSE: // Did We Receive A Close Message?
{
PostQuitMessage(0); // Send A Quit Message
return 0; // Jump Back
}
case WM_KEYDOWN: // Is A Key Being Held Down?
{
keys[wParam] = TRUE; // If So, Mark It As TRUE
return 0; // Jump Back
}
case WM_KEYUP: // Has A Key Been Released?
{
keys[wParam] = FALSE; // If So, Mark It As FALSE
return 0; // Jump Back
}
case WM_SIZE: // Resize The OpenGL Window
{
ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height
return 0; // Jump Back
}
}
// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
int WINAPI WinMain( HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
{
MSG msg; // Windows Message Structure
BOOL done=FALSE; // Bool Variable To Exit Loop
// Ask The User Which Screen Mode They Prefer
if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
{
fullscreen=FALSE; // Windowed Mode
}
// Create Our OpenGL Window
if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
{
return 0; // Quit If Window Was Not Created
}
while(!done) // Loop That Runs While done=FALSE
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting?
{
if (msg.message==WM_QUIT) // Have We Received A Quit Message?
{
done=TRUE; // If So done=TRUE
}
else // If Not, Deal With Window Messages
{
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
else // If There Are No Messages
{
// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
if (active) // Program Active?
{
if (keys[VK_ESCAPE]) // Was ESC Pressed?
{
done=TRUE; // ESC Signalled A Quit
}
else // Not Time To Quit, Update Screen
{
DrawGLScene(); // Draw The Scene
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}
}
if (keys[VK_F1]) // Is F1 Being Pressed?
{
keys[VK_F1]=FALSE; // If So Make Key FALSE
KillGLWindow(); // Kill Our Current Window
fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode
// Recreate Our OpenGL Window
if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
{
return 0; // Quit If Window Was Not Created
}
}
}
}
// Shutdown
KillGLWindow(); // Kill The Window
return (msg.wParam); // Exit The Program
}
If you really, really want to do it yourself, you can still have a look at how GLFW does it. In its source directory, you have a win32-specific directory, in which you have a windowing-specic .c file. You should find everything you need in this file.
This page of the OpenGL Wiki could help you, too.
The best way is NOT to do it yourself. OpenGL context creation is a bottomless abyss of complexity. You have lots of tools that can do the dirty work for you, and what's more, it'll work on Linux and Mac too
GLFW, FreeGlut, SDL, SFML are probably the most common.
See GLFW's user guide, for instance, to see how easy these libs make it to create a window :
glfwInit();
glfwOpenWindow( 300,300, 0,0,0,0,0,0, GLFW_WINDOW );
// bam, you're done

Resources