Processing WM_PAINT - c

I have read many examples on the internet but I'm still stuck. I'm trying to process the WM_PAINT message sent to my application.
In my application, I always draw in the same DC, named g_hDC. It works perfectly. When WM_PAINT is received, I just try to draw the content of my g_hDC into the DC returned by BeginPaint. I guess g_hDC contains the last bitmap that I drawn. So I just want to restore it.
case WM_PAINT:
PAINTSTRUCT ps;
int ret;
HDC compatDC;
HDC currentDC;
HDC paintDC;
HBITMAP compatBitmap;
HGDIOBJ oldBitmap;
paintDC = BeginPaint(g_hWnd, &ps);
currentDC = GetDC(g_hWnd);
compatDC = CreateCompatibleDC(paintDC);
compatBitmap=CreateCompatibleBitmap(paintDC, CONFIG_WINDOW_WIDTH, CONFIG_WINDOW_HEIGHT);
oldBitmap=SelectObject(compatDC, compatBitmap);
ret = BitBlt(compatDC,
ps.rcPaint.left,
ps.rcPaint.top,
ps.rcPaint.right - ps.rcPaint.left,
ps.rcPaint.bottom - ps.rcPaint.top,
currentDC,
ps.rcPaint.left,
ps.rcPaint.top,
SRCCOPY);
ret = BitBlt(paintDC,
ps.rcPaint.left,
ps.rcPaint.top,
ps.rcPaint.right - ps.rcPaint.left,
ps.rcPaint.bottom - ps.rcPaint.top,
compatDC,
ps.rcPaint.left,
ps.rcPaint.top,
SRCCOPY);
DeleteObject(SelectObject(compatDC, oldBitmap));
DeleteDC(compatDC);
DeleteDC(currentDC);
EndPaint(g_hWnd, &ps);
break;
But it just draws a white rectangle ... I tried many possibilities and nothing works. Can you please help me?

There are a number of things you are doing wrong.
First, your saving g_hDC is relying on an implementation detail: you notice that the pointers are the same, and thus save the pointer. This may work in the short term for a variety of reasons related to optimization on GDI's part (for instance, there is DC cache), but will stop working eventually, when it is least convenient. Or you may be tempted to use the DC pointer when you don't have the DC, and will scribble over something else (or fail to do so due to GDI object thread affinity).
The correct way to access the DC of a window outside its WM_PAINT is by calling GetDC(hwnd).
CreateCompatibleDC() creates an in-memory DC compatible with hdc. Drawing to compatDC is not enough to draw to hdc; you need to draw back to hdc after you draw to compatDC. For your case, you will need to have two BitBlt() calls; the second one will blit back from compatDC onto hdc. See this sample code for details.
You cannot DeleteObject() a bitmap while you have it selected into a DC. Your SelectObject(compatDC, oldBitmap) call needs to come before DeleteObject(compatBitmap). (This is what i486 was trying to get at in his answer.)
(I'm sure this answer is misleading or incomplete in some places; please let me know if it is.)

Use this to delete bitmat: DeleteObject( SelectObject(compatDC,oldBitmap) ); - without DeleteBitmap on prev line. SelectObject returns current (old) selection as return value - and you delete it. In your case you are trying to delete still selected bitmap.
PS: I don't see CreateCompatibleDC - where you are creating compatDC? Add compatDC = CreateCompatibleDC( hdc ); before CreateCompatibleBitmap.

Related

How do I use SDL_LockTexture() to update dirty rectangles?

I'm migrating an application from SDL 1.2 to 2.0, and it keeps an array of dirty rectangles to determine which parts of its SDL_Surface to draw to the screen. I'm trying to find the best way to integrate this with SDL 2's SDL_Texture.
Here's how the SDL 1.2 driver is working: https://gist.github.com/nikolas/1bb8c675209d2296a23cc1a395a32a0d
And here's how I'm getting changes from the surface to the texture in SDL 2:
void *pixels;
int pitch;
SDL_LockTexture(_sdl_texture, NULL, &pixels, &pitch);
memcpy(
pixels, _sdl_surface->pixels,
pitch * _sdl_surface->h);
SDL_UnlockTexture(_sdl_texture);
for (int i = 0; i < num_dirty_rects; i++) {
SDL_RenderCopy(
_sdl_renderer, _sdl_texture, &_dirty_rects[i], &_dirty_rects[i]);
}
SDL_RenderPresent(_sdl_renderer);
I'm just updating the entire surface, but then taking advantage of the dirty rectangles in the RenderCopy(). Is there a better way to do things here, only updating the dirty rectangles? Will I run into problems calling SDL_LockTexture and UnlockTexture up to a hundred times every frame, or is that how they're meant to be used?
SDL_LockTexture accepts an SDL_Rect param which I could use here, but then it's unclear to me how to get the appropriate rect from _sdl_surface->pixels. How would I copy out just a small rect from this pixel data of the entire screen?

How to make a hole on top of the object in openGL cubestack?

i want to make a hole in openGL cube.i have tried certain methods like using stencils and alpha blending.but problem with stencils is it is dividing and displaying the only half part.My requirement is i have to stack cubes and should make a user specified number of hole(rectangle/ellipse shaped)to only the top object.I am able to stack the objects but not able to make a hole if needed. I am new to openGL and i din't find any direct solution for this.can someone give a sample program for this requirement?
Stencils code:
glClear(GL_STENCIL_BUFFER_BIT);
glColorMask(false, false, false, false);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_EQUAL, 0, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glDisable(GL_DEPTH_TEST);
glColor4f(0,0,1,1.0f);
//code for cube
glEnable(GL_DEPTH_TEST);
glColorMask(true, true, true, true);
glStencilFunc(GL_ALWAYS,0, 1);
glStencilOp(GL_REPLACE,GL_KEEP, GL_ZERO);
//code for cylinder
glDisable(GL_STENCIL_TEST);
In your sample, why do you render hole after the cube?? if you want your stencil to do something you should do the opposite.
With this pseudo code, hole should be plane mesh or nearly.
-enable depth test if not already done; (depth test should not be disabled, if the point of view place hole on back faces, you dont want to have it reflected in front...)
-Enable stencil test;
-set colormask to false;
-set stencil op replace; (if your hole are rendered and maybe moving each frame,
use replace to update the stencil)
-set stencil func always 1 1; (if you wants your hole to be rendered into the stencil
buffer you have to pass always)
-render your hole mesh with your current model view matrices;
-restore colormask to true;
-set stencilfunc notequal 1 1; (dont draw if something appear in stencil at this place)
-set stencil op keep:; (keep in any case)
-draw your scene: holes will be masked;
Use FBO to Create new texture with alpha channel used for creating the hole.

simple c programming gui

I developed the steam table equation solver in C language...but the inputing the values in black screen console is boring.
So I strictly wanted to create simple GUI in C.
I searched for hello world codes, all were pretty long. But this was the only one I understood.
#include <windows.h>
int main()
{
MessageBoxA( NULL, "Hello World!", "Hello", MB_OK );
}
By using a gui builder for C, i got this code, now I was thinking how to scan values from TEXTBOX1 and TEXTBOX2 on Clicking of COMMANDBUTTON1 and display the output in TEXTBOX3?
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <windowsx.h>
#include <commctrl.h>
#include "hello.auto.h"
HWND hwnd_Label1, hwnd_Label2, hwnd_TextBox1, hwnd_TextBox2, hwnd_CommandButton1,
hwnd_TextBox3;
HFONT MSSansSerif_8pt;
void CreateChildWindows(HWND hwndMainWindow, HINSTANCE hInstance)
{
InitCommonControls();
MSSansSerif_8pt = CreateFont(-11,0,0,0,FW_NORMAL,0,0,0,0,0,0,0,0,"MS Sans Serif");
hwnd_Label1 = CreateWindowEx(0, "Static", "Pressure",
WS_CHILD | WS_VISIBLE,
11, 55, 95, 38, hwndMainWindow,
(HMENU)Label1, hInstance, NULL);
SetWindowFont(hwnd_Label1, MSSansSerif_8pt, TRUE);
hwnd_Label2 = CreateWindowEx(0, "Static", "Temperature",
WS_CHILD | WS_VISIBLE,
11, 110, 95, 38, hwndMainWindow,
(HMENU)Label2, hInstance, NULL);
SetWindowFont(hwnd_Label2, MSSansSerif_8pt, TRUE);
hwnd_TextBox1 = CreateWindowEx(WS_EX_CLIENTEDGE, "Edit" , NULL,
WS_CHILD | ES_WANTRETURN | WS_VISIBLE,
187, 55, 83, 35, hwndMainWindow,
(HMENU)TextBox1, hInstance, NULL);
SetWindowFont(hwnd_TextBox1, MSSansSerif_8pt, TRUE);
hwnd_TextBox2 = CreateWindowEx(WS_EX_CLIENTEDGE, "Edit" , NULL,
WS_CHILD | ES_WANTRETURN | WS_VISIBLE,
187, 99, 83, 35, hwndMainWindow,
(HMENU)TextBox2, hInstance, NULL);
SetWindowFont(hwnd_TextBox2, MSSansSerif_8pt, TRUE);
hwnd_CommandButton1 = CreateWindowEx(0, "Button", "CommandButton1",
WS_CHILD | BS_MULTILINE | BS_PUSHBUTTON | WS_VISIBLE,
308, 77, 117, 52, hwndMainWindow,
(HMENU)CommandButton1, hInstance, NULL);
SetWindowFont(hwnd_CommandButton1, MSSansSerif_8pt, TRUE);
hwnd_TextBox3 = CreateWindowEx(WS_EX_CLIENTEDGE, "Edit" , NULL,
WS_CHILD | ES_WANTRETURN | WS_VISIBLE,
66, 220, 385, 35, hwndMainWindow,
(HMENU)TextBox3, hInstance, NULL);
SetWindowFont(hwnd_TextBox3, MSSansSerif_8pt, TRUE);
return;
}
HWND GetItem(int nIDDlgItem)
{
switch(nIDDlgItem)
{
case -1:
return GetParent(hwnd_Label1);
case Label1:
return hwnd_Label1;
case Label2:
return hwnd_Label2;
case TextBox1:
return hwnd_TextBox1;
case TextBox2:
return hwnd_TextBox2;
case CommandButton1:
return hwnd_CommandButton1;
case TextBox3:
return hwnd_TextBox3;
default: return NULL;
}
}
void Form_Unload(HWND hMainWnd)
{
DeleteFont(MSSansSerif_8pt);
return;
}
I tried many times, but failed. Even if you people give me links of good sites, then I will be greatful.
You're looking for a good book on Win32 API programming using C. And you're in luck, there's a great book that pretty much everyone uses to learn it. It's written by Charles Petzold, and it's called (aptly enough) Programming Windows. You want the 5th edition, which is the most recent version that discusses Win32 programming.
There are also various tutorials available online if you search for "Win32 programming". However, a number of them contain some errors and misunderstandings (like the difference between ANSI and Unicode strings), and the good ones are rather short and incomplete. You won't learn everything you need to know to write a non-trivial program from online tutorials, but you should be able to get something really simple up on the screen. This one by theForger is one I've seen recommended many times.
Be warned, though, that writing GUI code (especially at such a low level) tends to be a lot more verbose than simply getting text onto the screen for a console program. You're going to end up writing a bunch of code that is used only to make the GUI work and has nothing to do with the logic of your program. It's much easier if you learn the C language first, and that's best done through simple console-type, text-only programs.
As for your specific question, you've created three textbox controls on the screen, named hwnd_TextBoxX, where X is a number between 1 and 3. As you probably already know, hwnd indicates a handle to a window (wnd), and so those variables hold handles to the textbox windows.
The Win32 API provides a GetWindowText function, which you can use to retrieve the text from a particular window. You pass it a handle to the desired window (hWnd), a pointer to a character buffer, and an integer value indicating the length of your buffer. Already, the ugly nature of the C language crops up—you have to understand how strings work in C in order to call the function correctly.
Once you've retrieved the string displayed in one of the textboxes, you can display it in another textbox window using the similar SetWindowText function, which takes only the window handle (hWnd) and a pointer to the buffer containing the string.
The code would look something like this:
// Get the text displayed in textbox 1
TCHAR szBuffer[100];
GetWindowText(hwnd_TextBox1, szBuffer, 100);
// Display that text in textbox 3
SetWindowText(hwnd_TextBox3, szBuffer);
To do this in response to a click on a button, you'll need to learn about the Win32 equivalent of "events"—window messages. Child windows, like button controls, send notification messages to their parent window (i.e., a dialog) when something potentially interesting happens, like the user clicks on them.
In particular, a button control sends its parent a BN_CLICKED notification through the WM_COMMAND message. By handling the WM_COMMAND message in your main window's window procedure (WndProc) method, you can check that the lParam parameter matches your button control's window handle (hWnd) and that the HIWORD(wParam) matches the BN_CLICKED notification code.
You definitely need a good book that contains step-by-step sample code for that one. It's a bit too difficult to explain thoroughly in a Stack Overflow answer.
Writing a GUI application using just the Win32 API is somewhat fun, but also tedious. It is much easier to use a framework of some sort. This doesn't mean it's impossible though. Here's a quick overview of how you do it.
First, you replace the main routine with WinMain. This routine is the new entry point of your application. It will be responsible for creating the windows and setting up a message dispatch loop.
Notice that I said "windows" and not just a "window". In WinAPI, every "control" you see on the "form" is a "window". The "form" itself is a window also. Every window has a window handle (HWND). You can make an application window using CreateWindow. This gets you a window handle that you can pass to the CreateChildWindows function that the GUI builder made for you. This will add child windows (the controls) to the application window.
Now you need to program all these windows. You do that by processing messages. When you create your application window, you need to supply a window procedure. This procedure will respond to messages as they come in. For example, a button click results in a WM_COMMAND message that you will have to handle. The last thing WinMain does is start a message processing loop that repeatedly calls your WndProc for any incoming message.
This will all start to make sense once you work through the tutorial linked in the other answer. Then you will probably get tired of this and pick up a GUI toolkit :)

Custom Find/Replace dialog box

First of all, please bear in mind that I'm new to Windows Programming. I'll try to cover my question in great detail, so that hopefully the answer will be too.
A short introduction:
I'm copying writing a Notepad-like application using Win32 API and pure C. For those of you familiar with Petzold's Windows Programming, this is a modified version of his POPPAD program which he used to describe Common Dialog Boxes. I'm writing this strictly for educational purposes, so please refrain from posting comments like "why you using old technology, use .NET", as those comments will not help me solve my problem :).
Description of a problem:
Petzold in his POPPAD program used Common Dialog Boxes to write this Notepad-like application. He used Edit Control to provide all the functions of a basic text editor. POPPAD, much like a Notepad, also had Find and Replace dialog boxes where you could, well, find stuff AND replace it! Mind boggling, I know.
So this is where I wanted to test my newly acquired knowledge from reading the past chapters, as I decided to write my very own Find and Replace dialog box. Granted, it would be in the simplest form possibly. How hard can it be? You have one text field where you enter some text and you have one fancy button which says "Find!" on it.
Now I'd like to remind you once more that I'm new to Windows programming, so excuse me for any possibly newbie questions. Also, I'd like to point out that I'll focus solely on making the Find dialog box working, as Replace shouldn't be too hard to implement then.
So I played with the resource editor in Visual Studio, and few hours later I got this:
(stackoverflow doesn't actually allows me to post images, so here's the link below)
http://i.imgur.com/R98x4.png
I named this dialog box "Find" (with the quotation marks), so I don't have to use MAKEINTRESOURCE macro in my program, as per Petzold's school of thought. I changed the caption of "Ok" button to "Find Next" and changed it's ID from IDOK to IDC_FIND. Also changed IDCANCEL to IDC_CANCEL and that single line Edit Control is IDC_FIND_FIND.
Now to the more serious things. In my main program's Windows Procedure, I have this piece of code:
case IDM_SEARCH_FIND:
hDlgModeless = CreateDialog (hInst, TEXT ("Find"),
hwnd, FindDlgProc) ;
return 0 ;
IDM_SEARCH_FIND is a message identifier of a Menu item, which when clicked should open up the Find dialog box. CreateDialog function is used to create a modeless dialog box and store it's handle into a global variable hDlgModeless. FindDlgProc is name of the dialog box procedure where (I think) all the code of finding the text should go.
So without further ado, here's the code of my Find dialog box procedure:
BOOL CALLBACK FindDlgProc (HWND hDlg, UINT message,
WPARAM wParam, LPARAM lParam)
{
static TCHAR szFindWhat[MAX_STRING_LEN]; //Text to find
static int iOffset ; //Offset from the beginning of Edit control to the result
int iLength, iPos, iSingleLength ; //Length of a main Edit control and single line Edit control
PTSTR pstrDoc, pstrPos ;
switch (message)
{
case WM_INITDIALOG:
return TRUE ;
case WM_COMMAND:
switch (LOWORD (wParam))
{
//If the button "Find Next" has been pressed, process all the logic of finding the text
case IDC_FIND:
// Get the text from a single-line edit control in Find dialog box
// and save it in szFindWhat variable
iSingleLength = GetWindowTextLength(GetDlgItem(hDlg, IDE_FIND_FIND)) ;
GetWindowText(GetDlgItem(hDlg, IDE_FIND_FIND), szFindWhat, iSingleLength) ;
// Get the text from a main Edit control, allocate memory for it
// and store it in pstrDoc variable
iLength = GetWindowTextLength (hwndEdit) ;
if (NULL == (pstrDoc = (PTSTR) malloc ((iLength + 1) * sizeof (TCHAR))))
return FALSE ;
GetWindowText (hwndEdit, pstrDoc, iLength + 1) ;
// Search the document for the find string
pstrPos = _tcsstr (pstrDoc + iOffset, szFindWhat) ;
free (pstrDoc) ;
// Return an error code if the string cannot be found
if (pstrPos == NULL)
return FALSE ;
// Find the position in the document and the new start offset
iPos = pstrPos - pstrDoc ;
iOffset = iPos + lstrlen (szFindWhat) ;
// Select the found text
SendMessage (hwndEdit, EM_SETSEL, iPos, iOffset) ;
SendMessage (hwndEdit, EM_SCROLLCARET, 0, 0) ;
case IDC_CANCEL:
DestroyWindow (hDlg) ;
hDlgModeless = NULL ;
break ;
}
break ;
case WM_CLOSE:
DestroyWindow (hDlg) ;
hDlgModeless = NULL ;
break ;
default:
return FALSE;
}
return FALSE ;
}
The only actual error I get here is that hwndEdit is undeclared identifier. hwndEdit is the main Edit control (not the single-line in Find dialog box). How do I get the handle to hwndEdit while I'm in a Find dialog box procedure?
I'd like to point out that I'm feeling a bit over my head here, so please say if I'm missing/doing wrong something obvious. I'm pretty sure that even if I fix the only error I'm getting, the program still won't work. Even though the concept of what I should be doing sounds fairly simple, actually programming that seems quite difficult :)
This is what the code above should do, in simplest form:
- Get the text from Find dialog box which I wish to search
- Get the text from main Edit control
- Do a substring search from the last offset (don't start from beginning every time)
- Find the position of a result and readjust offset
- Select the found text
I know I haven't really asked a direct question here, well I guess the direct question would be: How do I make this work? :) But more importantly it would be to understand how this exactly works. I'd appreciate if you can provide me with an elaborate answer. Thanks for all the help!
It looks like you're very close, you just need to get the hwndEdit from your main window. You passed your main window's handle in as a parent to your dialog box, so you should be able to get the parent window of your dialog box like so:
HWND hwndParent = GetParent(hDlg);
After that you can get the edit control from that parent by referencing the edit control ID in your main window definition. Something like this (assuming the control ID is IDC_EDIT):
HWND hwndEdit = GetDlgItem(hwndParent, IDC_EDIT);

ShowWindow within WM_CREATE

The way I see it, one use of a Window Procedure's WM_CREATE message is to relieve the caller of the burden of executing static code at window initialization. My window is to execute some code in the WM_CREATE message, including the ShowWindow function. I also want the ShowWindow to behave properly according to the nCmdShow parameter in WinMain. So here is pseudo-code to show how I have things set up:
int g_nCmdShow;
WinMain(..., int nCmdShow)
{
g_nCmdShow = nCmdShow;
...
CreateWindow(..., WM_OVERLAPPEDWINDOW, ...)
...
}
WndProc()
{
...
WM_CREATE:
...
ShowWindow(hWnd, g_nCmdShow);
...
...
}
So I set up the program to run Minimized (using Windows XP I created a shortcut to the .exe, and set up the properties of it accordingly), and it displays on the taskbar minimized but it does not restore when I click on it. Likewise, if I run it Maximized, it does not behave correctly when I click the maximize button (to un-maximize it).
What is the correct way to use nCmdShow-compatible ShowWindow within the WM_CREATE message?
The problem is that the window's restore bounds get affected by this. They become the size of the window after WM_CREATE returns. You would have to modify your code to re-establish those restore bounds:
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, 300, 200, NULL, NULL, hInstance, NULL);
WINDOWPLACEMENT wp;
GetWindowPlacement(hWnd, &wp); // <= Note wp.rcNormalPosition after this call!
RECT rc = {100, 100, 400, 300};
wp.rcNormalPosition = rc;
SetWindowPlacement(hWnd, &wp);
You're not ahead by doing it this way.
If you absolutely have to keep it in the WndProc, try
case WM_CREATE:
PostMessage(hwnd,WM_APP,0,0);
break;
case WM_APP:
ShowWindow(hwnd,SW_SHOW);
break;
But if this is so important, why not just have a helper function that creates the window and calls ShowWindow? MyWindowType_Create(...) etc
Having the window show itself, or set its own position, is a bad design choice that goes against how WinAPI was meant to be used. The right place to do these decisions is in the code that creates the window. It's already reflected in the fact that the CreateWindow is responsible for the initial window placement and WS_VISIBLE style.
In your code you should call ShowWindow in WinMain, which will also eliminate the need for the g_nCmdShow global:
WinMain(..., int nCmdShow)
{
...
hWnd = CreateWindow(..., WM_OVERLAPPEDWINDOW, ...)
ShowWindow(hWnd, nCmdShow);
...
}
WndProc()
{
...
WM_CREATE:
...
...
}
WM_CREATE is rather responsible for initializing window-class specific behavior. Creating child windows or initializing internal data structures and the cbWndExtra slots are examples of that (e.g. think of implementing a list-box).
Can you handle WM_WINDOWPOSCHANGED and override the window size the first time the window is restored? Use GetWindowPlacement to find out if the window got restored.

Resources