Category Archives: Windows Programming

Double Buffering technique in MFC for Flicker Free drawing

Visual Programming

Flickering is caused in a window,  by painting,  in two steps.

(1) Erasing the window contents in OnEraseBkgnd.  By default MFC does this.

(2) Painting new contents in OnPaint or OnDraw.

Double buffering eliminates this two-step process by overriding OnEraseBkgnd and including the erase in OnPaint/OnDraw to an off-screen image.

1. Overriding the OnEraseBkgnd function:

  • Add a message handler for WM_ERASEBKGND in your Windows application.
  • Once added it looks like the below one:
  • BOOL CExampleView::OnEraseBkgnd(CDC* pDC) 
    {
          // TODO: Add your message handler code here and/or call default
          return CView::OnEraseBkgnd(pDC);
    }
    
    Now change the return value to any non-zero value and comment the default proced-ure.
    BOOL CExampleView::OnEraseBkgnd(CDC* pDC) 
    {
          return TRUE;
    }

2. Now In the OnPaint/OnDraw do the following steps:

1.  Create a Memory DC for the View DC as below:

               CreateCompatibleDC(pDC);

2.   Create the bitmap in memory…

View original post 78 more words

Windows API Programming using C/C++

English: .NET Stack and Win32/64 API comparison.

English: .NET Stack and Win32/64 API comparison. (Photo credit: Wikipedia)

Windows Operating system is undoubtedly has a major market share of desktop and laptop machines. Referring to Wikipedia, it is about 80% of the PC machines running one of the many versions of Windows.   Here I am not going to discuss the pros and cons of using Windows over other available OS choices but I only want to emphasize that knowing how to program applications for Windows can give a major boost to your career growth.

There are many available options for programming windows application. Keeping Windows 8 metro style application apart, all other versions of windows and even Windows 8 desktop side mainly rely on Windows API. (Though Windows RT underneath of Windows 8 metro style (or window store) apps is also based on Windows API).

You will normally found two terms used for Windows API, win32 and win64 for Windows 32 bit architecture and Windows 64 bit architecture. But the difference is so minute as far as programming is concerned that if you knew one, you already know the other.  One of the basic differences is the pointer address space which is 64 bit in case of Win64 API which means you can access 8 terabyte of memory, at least in theory.

We have found many wrapper frameworks of Windows API, like MFC (Microsoft Foundation Classes) and the famous .Net. But let me tell you these all are just wrappers of windows API in effort to simplify and increase productivity. But these frameworks also come with some costs, in terms of efficiency and control. Folks, who knew C/C++ and any other managed language as well, will understand what I am trying to say here.

If you want to learn any of these wrapper frameworks, it is a good idea to have a feel of Windows API to know and learn how Windows operating system internally works. Windows API exposes lowest level of operating system functionality and gives you complete control and power.

With this little motivation, I will try to show you and gives you a feel of Windows API programming using C and C++ with a serious of articles. I am not calling these articles as tutorials because these are not merely tutorials but I will try to take a little deeper dive into Windows API.

I will start with the legendry very first program of any computer programming language, the “Hello World” program. I will show you each line of code and then explain it in a little detail and at the end you can find the complete code in one place, which you can copy and paste and run.

I am assuming that you people already understand C/C++ syntax and have experience in console application programming. So I am not going to explain C/C++ syntax, what a header file is, what classes in case of C++ are and how to compile your code. I will focus just on Win API.

A minor point can be noted here that many or I would say all Windows programs and Win API use a system called “Hungarian notation” for naming variables. This system involves prefacing the variable name with a short prefix that indicates the variable’s data type. I’ll discuss this concept later in detail.

Hello World – Win API version using C/C++”

#include <windows.h>

It begins by including a header file that you will find at the top of every Win API program written in C or C++.

WINDOWS.H is a master header file which includes many other Win API header files, some of those include many other header files as well. The most important basic of these header files are stated below:

  • WINDEF.H                      it has basic type definitions.
  • WINNT.H                        it has type definitions for Unicode support.
  • WINBASE.H                  it has kernel functions.
  • WINUSER.H                 it has user interface functions.
  • WINGDI.H                     it has graphics device interface functions.

These header files have definations of all the Windows data types, function calls, data structures, and constant identifiers. These are an important part of Windows documentation and opening one of them and trying to understand it is really a good idea for learning more about windows API.

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow)

As every C/C++ program has an entry point, a windows program also has an entry point. In case of windows program, it is WinMain instead of main of C/C++. It is declared in WINBASE.H as below:

Int
WINAPI
WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd
);

Return type is int and The WINAPI identifier is defined in WINDEF.H with the statement:

#define WINAPI __stdcall

This statement specifies a calling convention that involves how machine code is generated to place function call arguments on the stack. Most Windows function calls are declared as WINAPI.

The first parameter to WinMain is something called an “instance handle.” In Windows programming, a handle is simply a number that an application uses to identify something. Do not confuse it with pointer as it is not a pointer. In this case, the handle uniquely identifies the program. It is required as an argument to some other Windows function calls.

The second parameter: In early versions of Windows, when you ran the same program concurrently more than once, you created multiple instances of that program. All instances of the same application shared code and read−only memory (usually resources such as menu and dialog box templates). A program could determine if other instances of itself were running by checking the hPrevInstance parameter. It could then skip certain chores and move some data from the previous instance into its own data area. In the 32bit and 64bit versions of Windows, this concept has been abandoned. The second parameter to WinMain is always NULL (defined as 0).

The third parameter to WinMain is the command line used to run the program. Some Windows applications use this to load a file into memory when the program is started. It is not relevant here. The variable type LPSTR can be read as Long Pointer to String. It is a heritage of 16bit windows where pointers were 16bit and use segment/offset addressing scheme. We can use the same safely with 32bit and 64bit versions of Windows. We can also use PSTR which is simply a pointer to string or can use Char * in its place.

The fourth parameter to WinMain indicates how the program should be initially displayed either normally or maximized to fill the window, or minimized to be displayed in the task list bar. We’ll see how this parameter is used later on.

The one and only line of WinMain would be as follows,

MessageBox (NULL, "Welcome to Windows Programming", "Welcome Message", 0) ;

The MessageBox function is designed to display short messages. The little window that MessageBox displays is actually considered to be a dialog box, we used to see in almost every session of Windows we run.

The first argument to MessageBox is normally a window handle. We’ll see what this means later. The second argument is the text string that appears in the body of the message box, and the third argument is the text string that appears in the caption bar of the message box.

The fourth argument to MessageBox can be a combination of constants beginning with the prefix MB_ that are defined in WINUSER.H. You can pick one constant from the first set to indicate what buttons you wish to appear in the dialog box:

  • #define MB_OK                                                              0x00000000L
  • #define MB_OKCANCEL                                              0x00000001L
  • #define MB_ABORTRETRYIGNORE                        0x00000002L
  • #define MB_YESNOCANCEL                                      0x00000003L
  • #define MB_YESNO                                                     0x00000004L
  • #define MB_RETRYCANCEL                                    0x00000005L

When you set the fourth argument to 0 in this function call, only the OK button appears. You can use the C (|) operator to combine one of the constants shown above with a constant that indicates which of the buttons is the default:

  • #define MB_DEFBUTTON1                          0x00000000L
  • #define MB_DEFBUTTON2                          0x00000100L
  • #define MB_DEFBUTTON3                          0x00000200L
  • #define MB_DEFBUTTON4                          0x00000300L

You can also use a constant that indicates the appearance of an icon in the message box:

  • #define MB_ICONHAND                              0x00000010L
  • #define MB_ICONQUESTION                     0x00000020L
  • #define MB_ICONEXCLAMATION            0x00000030L
  • #define MB_ICONASTERISK                        0x00000040L

Some of these icons have alternate names:

  • #define MB_ICONWARNING MB_ICONEXCLAMATION
  • #define MB_ICONERROR MB_ICONHAND
  • #define MB_ICONINFORMATION MB_ICONASTERISK
  • #define MB_ICONSTOP MB_ICONHAND

There are a few other MB_ constants, but you can consult the header file yourself or in the documentation.

In this program, the MessageBox function returns the value 1, but it’s more proper to say that it returns IDOK, which is defined in WINUSER.H as equaling 1. Depending on the other buttons present in the message box, the MessageBox function can also return IDYES, IDNO, IDCANCEL, IDABORT, IDRETRY, or IDIGNORE.

Now below is the complete code of your very first Windows program which you can copy/paste or type in your favorite C/C++ IDE, compile and run.

#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
MessageBox (NULL, "Welcome to Windows Programming", "Welcome Message", 0) ;
return 0 ;
}

Experiment by your own is the key of learning and I will get back to you with next article on Windows API very soon.

Fragments taken from Charles Petzold – programming Windows

how to capture screen in a dual monitor system VC++

Visual Programming

Use the SM_CXVIRTUALSCREEN and SM_CYVIRTUALSCREEN as the parameter for GetSystemMetrics function.

Ex:  GetSystemMetrics(SM_CXVIRTUALSCREEN);

A Virtual Screen a logical rectangle which will wrap across all the monitors present for a desktop.  The SM_CXVIRTUALSCREEN and SM_CYVIRTUALSCREEN returns these logical x, y coordinates of the virtual screen.

We can use Dual Monitor API available for windows desktop development to get the details of each and every monitor individually.  The following piece of code will give the information about how to do it:

void ClipOrCenterRectToMonitor(LPRECT prc, UINT flags) { HMONITOR hMonitor; MONITORINFO mi; RECT rc; int w = prc->right - prc->left; int h = prc->bottom - prc->top; // // get the nearest monitor to the passed rect. // hMonitor = MonitorFromRect(prc, MONITOR_DEFAULTTONEAREST); // // get the work area or entire monitor rect. // mi.cbSize = sizeof(mi); GetMonitorInfo(hMonitor, &mi); if (flags & MONITOR_WORKAREA) rc = mi.rcWork; else rc = mi.rcMonitor; // // center or clip…

View original post 73 more words

In-depth look at WinRT

ecogamedesign

A little article I found Yesterday. It’s quite old but very interesting to read 🙂

Turning to the past to power Windows’ future: An in-depth look at WinRT

View original post

The Challenge of Writing Correct System Calls

William A Adams

If you are a veteran of using Windows APIs, you might be familiar with some patterns. One of them is the dual return value:

int somefunc();

Documentation: somefunc(), will return some value other than 0 upon success. On failure, it will return 0, and you can then call GetLastError() to find out which error actually occured…

In some cases, 0 means error. In some cases, 0 means success, and anything else is actually the error. In some cases they return BOOL, and some BOOLEAN (completely different!).

Another pattern is the “pass me a buffer, and a size…”

int somefunc(char *buff, int sizeofbuff)

Documentation: Pass in a buffer, and the size of the buffer. If the ‘sizebuff’ == 0, then the return value will indicate how many bytes need to be allocated in the buffer, so you can call the function again.

A slight variant is this one:

int somefunc(char *buff…

View original post 741 more words