Sunday 31 July 2011

Multithreading MFC Part-I

Part I of this tutorial covers basic concept of multithreading. If you have never used multithreading in your application and wish to know how to use multithreading in your applications and why, Then this article might be useful for you. I will cover samples and advanced topics of multithreading in the Part II of this tutorial.Threading Concepts:A thread is a path of execution. Each application has a default thread called 'Main Thread' or 'Primary
Thread
'. You can create multiple threads in your program. Other threads besides primary threads are called
'Secondary Threads'. Each process has at least one of more threads.
Multithreading:Running more than one thread simultaneously is multithreading.Why multiple threads?Sometimes your program requirement is to do more than one task simultaneously. For example, if you have a program which reads a large database, generate some reports and print them. Suppose generating and printing these reports take few hours. If you don't use multithreading, you can't do anything if you are generating reports. Now what if you want to feed some input data when its generating time consuming reports? In present scenario you can't. But your program supports multithreading, one thread can takes care of reports and you can use other thread to feed input data.Did you use FrontPage or MS Word? This is one good example of multithreading. When you type wrong spelling of any word, it let you know by drawing an underline. It does spell checking in a background thread and you even notice it. Neat? huh?MFC and Multithreading:MFC supports two types of threading: User Interface Threads ( UI Threads ) and Worker Threads. UI threads have a GUI with a message pump so user can trap the messages such as mouse or keyboard. Worker thread doesn't have message pump and used to execute background talks such as big calculations, or generating reports.Before we create our secondary threads, lets see the definition of one important function.afxBeginThread: - This function creates a new thread by calling CWinThread's CreateThread function and
returns a CWinThread object. Here is syntax:
CWinThread* AfxBeginThread( AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );CWinThread* AfxBeginThread( CRuntimeClass* pThreadClass, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );
Parameter Description
pfnThreadProc controlling function, cannot be NULL. This function must be declared as follows: UINT MyControllingFunction( LPVOID pParam );
pThreadClass The RUNTIME_CLASS of an object derived from CWinThread.
pParam Parameter to be passed to the controlling function as shown in the parameter to the function declaration in pfnThreadProc.
nPriority Thread priority. See below table.
nStackSize Specifies the size in bytes of the stack for the new thread. If 0, the stack size defaults to the same size stack as the creating thread.
dwCreateFlags additional flag and can be any of these two CREATE_SUSPENDED or 0. CREATE_SUSPENDED starts the thread with a suspend count of one. The thread will not execute until ResumeThread is called. 0 Start the thread immediately after creation.
lpSecurityAttrs Points to a SECURITY_ATTRIBUTES structure. See SECURITY_ATTRIBUTES for more details.

Thread Priorities:
Priority Meaning
THREAD_PRIORITY_ABOVE_NORMAL Indicates 1 point above normal priority for the priority class.
THREAD_PRIORITY_BELOW_NORMAL Indicates 1 point below normal priority for the priority class.
THREAD_PRIORITY_HIGHEST Indicates 2 points above normal priority for the priority class.
THREAD_PRIORITY_IDLE Indicates a base priority level of 1 for IDLE_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, ABOVE_NORMAL_PRIORITY_CLASS, or HIGH_PRIORITY_CLASS processes, and a base priority level of 16 for REALTIME_PRIORITY_CLASS processes.
THREAD_PRIORITY_LOWEST Indicates 2 points below normal priority for the priority class.
THREAD_PRIORITY_NORMAL Indicates normal priority for the priority class.
THREAD_PRIORITY_TIME_CRITICAL Indicates a base priority level of 15 for IDLE_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, ABOVE_NORMAL_PRIORITY_CLASS, or HIGH_PRIORITY_CLASS processes, and a base priority level of 31 for REALTIME_PRIORITY_CLASS processes.
Creating User Interface Thread:A UI thread has a GUI with a message pump and commonly used to handle user input. The main thread in your application is a UI thread. Here are few steps to create a UI thread:1. Derive a class from CWinThread and override its functions

Function name Purpose
InitInstance Perform thread instance initialization. Must be overridden.
Run Controlling function for the thread. Contains the message pump. Rarely overridden.
OnIdle Perform thread-specific idle-time processing. Not usually overridden.
PreTranslateMessage Filter messages before they are dispatched to TranslateMessage and DispatchMessage. Not usually overridden.
ProcessWndProcException Intercept unhandled exceptions thrown by the thread's message and command handlers. Not usually overridden.
ExitInstance Perform cleanup when thread terminates. Usually overridden.
2. Create a thread by calling afxBeginThread with RUNTIME_CLASS of the class you derived from CWinThread as first parameter of afxBeginThread function. Rest parameters are optional. See afxBeginThread for more details. Creating a Worker Thread:A worker thread is commonly used to handle backgrounds tasks that the you shouldn't have to wait to continue using your application. Creating a secondary thread is pretty easy task. There are only two steps:Step 1. Create a function which will be executed by secondary thread. This function has your code which suppose to executed in secondary thread.UINT ProcName(LPVOID param)
{
{
Do Something
}
return 0;
}
Step 2. Create thread by calling MFC function AfxBeginThread.AfxBeginThread( ProcName, param, priority );This thread remains active as long as thread's function is executing. When thread function exits, the thread is
destroyed. You can set thread priorities according to your requirement.
Sample Example:Step 1. Create an SDI application with all default settings accept turn off all check boxes of Step 4 of 6 of
AppWizard.

Step 2. Add a menu item 'Thread' with a sub menu item 'Start Thread'. Write corresponding command handler
using ClassWizard.

Step 3. Type this code below and here is how your function look like:
void CMainFrame::OnThreadStart()
{
// CODE_START
HWND hWnd = GetSafeHwnd();
AfxBeginThread( mcProc, hWnd, THREAD_PRIORITY_NORMAL );
// CODE_END
}
Step 4. Create a global function. Type this code just before this command handler function OnThreadStartUINT mcProc(LPVOID param)
{
::MessageBox( (HWND)param, "Thread Start", "Secondary Thread", MB_OK );
return 0;
}


Step 5. Build, and execute your project and click Start Thread menu item.

Thread Synchronization:If more than one thread uses same resources ( variables such as a link list ) then it is very important to provide a synchronization between them. Ok let's say, two threads A and B are using a list. When thread A is reading data, thread B is writing data. To avoid data inconsistency thread synchronization is must.

Win 32 supports 4 types of thread synchronization objects:
  •  Events
  • Critical Sections
  • Mutexes
  • Semaphores


Events:Events are used to provide synchronization between two or more concurrently running threads. An event is a BOOL type variable. This can have two states, either set or reset. If two threads are using same list, and say ThreadA is writing data to the list, then ThreadA will reset that event. Now if ThreadB wants to access that data, it will first see if that event is set or not. If it is not set then it will wait. ThreadA will set this event as it is done writing data to the list. One this event is set, ThreadB has the acccess.MFC's CEVent class encapsulate this functionality. It provides two members SetEvent and ResetEvent.Critical Sections:A critical section is an area of the code which is locked by one thread and this thread doesn't release this area until it is done it job. During CS, only one thread can access that code. Let's say, ThreadA is writing some data to a data structure, it will lock that area of code until it is done writing and it will only unlock after it is done.

MFC's CCriticalSection class encapsulate this functionality. It provides members functions Lock and UnLock. It's easy to use CS in your applications:CCriticalSection cs;
.....
....
// ThreadA writes data to an array
cs.Lock();
// Write data to an array
cs.Unlock();
....// ThreadB reads data to an array
cs.Lock();
// Read data from an array
cs.Unlock();


Mutexes:Critical Sections can only work for single process while mutexes can be used for mutiple process using multiple
threads. You can use mutexes for multiple threads in same process too. Let's say, you have one txt file. You
are running two processes ProcA and ProcB. You want to make sure that ProcB can't have access to the txt file
if ProA is reading/writing it.
CMutex mx( FALSE, "tada");
.....
....
// ProcA writes data to the file
mx.Lock();
// Writes data
mx.Unlock();
....
CMutex mx( FALSE, "tada");
// ProcB writes data to the file
mx.Lock();
// Writes data
mx.Unlock();
We will see how to use in our examples.

Semaphores:Semaphores can be used to synchronize threads of a single process or multiple processes. The use of semaphores depends of number of resources available. CSemaphore class of MFC also have Lock and Unlock functions but it works in different way. Initially you have to allocate available resources. Locking a semaphore decrements a resource count and unlocking it increases the resource count. When resource count is 0, that means there are no resources available. Rest of the threads have to wait until another threads free the resources.CSemaphore cph( 1, 5) ; // This means initial resource count 1 with max 5 resources
....
cph.Lock(); // decrement count
// access the resource
cph.Unlock(); // increment count
We will see how to use in our examples.

Thread Termination and other operations:
There are different ways to terminate a thread.
1. Normal Thread Termination :For a worker thread, when a thread exits its controlling function, call either AfxEndThread function or a return 0. For a user-interface thread, ::PostQuitMessage. The  ::PostQuitMessage takes is the exit code of the thread. Call GetExitCodeThread  to get the exit code of a thread.  Return 0 is for successful completion.
2. Premature Thread Termination:

AfxEndThread is used to terminate a thread from within the thread. Pass the desired exit code as the only parameter. This stops execution of the thread, deallocates the thread's stack, detaches all DLLs attached to the thread, and deletes the thread object from memory.

Suspending and Resuming a Thread:
You can use CWinThread's ResumeThread and SuspendThead to resume and suspend a thread.
Thread Sleep:
You can put a thread to sleep by using Sleep Win32 API.::Sleep(1000);
Debugging Multithreading Applications:
Debugging a multithreaded application is not easy task. The best thing to to avoid bugs. There are two most common problems in multithreading applications. One is deadlock and other is access violation.
The deadlock situation occurs when multiple threads try to lock same resource at the same time. For example, say your application has two threads Thread1 and Thread2. Thread1 locks resource ResA and Thread2 locks ResB. Now Thread1 tries to lock ResB but wait to unlock ResA until it locks RestB which is already locked by Thread2. And Thread2 tries to lock ResA and wait to unlock ResB until it locks ResA.
Other problem in multithreaded applications are access violation. The main reason of access violation is when more than one thread try to access the same memory simultaneously or when shared memory has been released by other thread. Or other reason may be when one thread try to access a variable which is released by another thread.
Now point comes how to debug this kind of applications? And the main problem is when you try to debug this kind of applications, you won't get access violation in debug mode. The reason might be that debugger has stopped the other thread.
First thing to avoid this situation is try to synchronize your code. Use thread synchronization methods to access shared memory and don't let this situation arrive. What if you can't avoid this situation?? Well .. You can try one of two ways. I use ASSERT and message boxes when application is not big. But if application is big then creating log file(s) is not a bad approach. You write your values to these log files with your custom comments. You can have a separate log file for each thread and some common log files.
Designing a Thread Safe Class:
Why thread safe class? A thread safe class is a class which doesn't need any synchronization mechanism when it is used in more than one thread or applications. The members of this class can be shared by multiple threads but there won't be any data inconsistency because your class provides thread safety internally.
Creating a thread safe class is pretty easy. Just wrap all of its member functions in Lock and Unlock. Hopefully you will see one example in my next part of this tutorial.
CAUTIONS:
Caution 1: MFC classes are not thread safe
MFC classes are not thread safe on object level. That means if you use same object in two threads, data may not be safe. For example, if you use a CFile object in two classes, you must use some synchronization scheme to make sure your data is safe or use two separate objects.
Caution 2: MFC Objects from Win32 Threads
If you want to use MFC objects in your secondary thread, you must create that thread using MFC ( above UI or Worker thread techniques ). If you have created a thread using _beginthread Win32 API then you can't use MFC objects in that thread.

COM Interview

Introduction

  1. What is IUnknown? What methods are provided by IUnknown? It is a generally good idea to have an answer for this question if you claim you know COM in your resume. Otherwise, you may consider your interview failed at this point. IUnknown is the base interface of COM. All other interfaces must derive directly or indirectly from IUnknown. There are three methods in that interface: AddRef, Release and QueryInterface.
  2. What are the purposes of AddRef, Release and QueryInterface functions? AddRef increments reference count of the object, Release decrements reference counter of the object and QueryInterface obtains a pointer to the requested interface.
  3. What should QueryInterface functions do if requested object was not found? Return E_NOINTERFACE and nullify its out parameter.
  4. How can would you create an instance of the object in COM? Well, it all depends on your project. Start your answer from CoCreateInstance or CoCreateInstanceEx, explain the difference between them. If interviewer is still not satisfied, you�ll have to explain the whole kitchen behind the scenes, including a difference between local server and inproc server, meaning and mechanism of class factory, etc. You may also mention other methods of object creation like CoGetInstanceFromFile, but discussion will likely turn to discussion of monikers then.
  5. What happens when client calls CoCreateInstance? Again, all depends on the level of detail and expertise of interviewer. Start with simple explanation of class object and class factory mechanism. Further details would depend on a specific situation.
  6. What the limitations of CoCreateInstance? Well, the major problems with CoCreateInstance is that it is only able to create one object and only on local system. To create a remote object or to get several objects, based on single CLSID, at the same time, one should use CoCreateInstanceEx.
  7. What is aggregation? How can we get an interface of the aggregated object? Aggregation is the reuse mechanism, in which the outer object exposes interfaces from the inner object as if they were implemented on the outer object itself. This is useful when the outer object would always delegate every call to one of its interfaces to the same interface in the inner object. Aggregation is actually a specialized case of containment/delegation, and is available as a convenience to avoid extra implementation overhead in the outer object in these cases. We can get a pointer to the inner interface, calling QueryInterface of the outer object with IID of the inner interface.
  8. C is aggregated by B, which in turn aggregated by A. Our client requested C. What will happen? QueryInterface to A will delegate request to B which, in turn, will delegate request for the interface to C. This pointer will be returned to the client.
  9. What is a moniker ? An object that implements the IMoniker interface. A moniker acts as a name that uniquely identifies a COM object. In the same way that a path identifies a file in the file system, a moniker identifies a COM object in the directory namespace.
  10. What�s the difference, if any, between OLE and COM? OLE is build on top of COM. The question is not strict, because OLE was built over COM for years, while COM as a technology was presented by Microsoft a few years ago. You may mention also that COM is a specification, while OLE is a particular implementation of this specification, which in today�s world is not exactly true as well, because what people call COM today is likely implementation of COM spec by Microsoft.
  11. What�s the difference between COM and DCOM? Again, the question does not require strict answer. Any DCOM object is yet a COM object (DCOM extends COM) and any COM object may participate in DCOM transactions. DCOM introduced several improvements/optimizations for distributed environment, such as MULTI_QI (multiple QueryInterface()), security contexts etc. DCOM demonstrated importance of surrogate process (you cannot run in-proc server on a remote machine. You need a surrogate process to do that.) DCOM introduced a load balancing.
  12. What is a dual interface? Dual interface is one that supports both - IDispatch interface and vtbl-based interface. Therefore, it might be used in scripting environment like VBScript and yet to use power and speed of vtbl-based interface for non-scripting environment. Discussion then may easily transform into analyzing of dual interface problems - be prepared to this twist.
  13. Can you have two dual interfaces in one class? Yes. You may have two dual interfaces in one class, but only one of them may be default. The bottom line is that you cannot work with two dual interfaces at the same time due to nature of dual interface! To support two dual interfaces in VB you would write something like:
        dim d1 as IDualInterface1
    dim d2 as IDualInterface2
    set d1 = new MyClassWithTwoDuals
    set d2 = d1
    In ATL�s class you would have to use macro COM_INTERFACE_ENTRY2(IDispatch,
    IDualInterface1), to distinguish between different dual interfaces.
  14. What is marshalling by value? Some objects can essentially be considered static: regardless of which methods are called, the state of the object does not change. Instead of accessing such an object remotely, it is possible to copy the static state of the object and create a new object with the same state information on the caller side. The caller won�t be able to notice the difference, but calls will be more efficient because they do not involve network round trips. This is called �marshaling by value�.
  15. What is a multi-threaded apartment (MTA)? Single-threaded apartment (STA)? This is pretty difficult question to describe shortly. Anyway, apartments were introduced by Microsoft in NT 3.51 and late Windows 95 to isolate the problem of running legacy non-thread safe code into multithreaded environment. Each thread was �encapsulated� into so called single-threaded apartment. The reason to create an object in apartment is thread-safety. COM is responsible synchronize access to the object even if the object inside of the apartment is not thread-safe. Multithreaded apartments (MTA, or free threading apartment) were introduced in NT 4.0. Idea behind MTA is that COM is not responsible to synchronize object calls between threads. In MTA the developer is responsible for that. See �Professional DCOM Programming� of Dr. Grimes et al. or �Essential COM� of Don Box for the further discussion on this topic.
  16. Let�s assume we have object B and aggregated object C (in-proc server), created by B. Can you access any interface of B from C? What�s the difference between aggregated and contained objects? Yes, you can. This is fundamental postulate of COM: �If you can get there from here, you can get there from anywhere�, i.e. QI�ing for IUnknown you may proceed and to get a pointer to any other interface, supported by the object. Aggregated object exposes its interface directly, without visible intervention of the object container. Contained object is created within the object container and its interfaces might be altered or filtered by the object container.
  17. What is ROT ? GIT ? Count pros and cons of both. By definition, running object table (ROT) is a globally accessible table on each computer that keeps track of all COM objects in the running state that can be identified by a moniker. Moniker providers register an object in the table, which increments the object�s reference count. Before the object can be destroyed, its moniker must be released from the table. Global Interface Table (GIT) allows any apartment (either single- or multi-threaded) in a process to get access to an interface implemented on an object in any other apartment in the process.
  18. If you have an object with two interfaces, can you custom marshal one of them? No! The decision to use custom marshaling is an all-or-nothing decision; an object has to custom marshal all its interfaces or none of them.
  19. Is there a way to register in-proc server without regsvr32.exe? Yes. Call DllRegisterServer() from the client. Do not forget to call DLLUnregisterServer() from the same client. You may also use Registrar object for the same purpose or use direct manipulation of the windows registry.
  20. What is VARIANT? Why and where would you use it? VARIANT is a huge union containing automation type. This allows easy conversion of one automation type to another. The biggest disadvantage of VARIANT is size of the union.
  21. How can you guarantee that only remote server is ever created by a client? Create an object (call CoCreateObjectEx()) with CLSCTX_REMOTE_SERVER flag.
  22. What is __declspec(novtable)? Why would you need this? __declspec(novtable) is a Microsoft�s compiler optimization. The main idea of this optimization is to strip the vtable initialization code from abstract class (for abstract class the vtable is empty, while it is initialized in contructor)
  23. What is an IDL? IDL stands for Interface Definition Language. IDL is the language to describe COM interfaces.
  24. What is In-proc? In-proc is in-process COM object, i.e. COM object that implemented as DLL and supposed to be hosted by a container. When you have to instantiate the in-proc object remotely, you may use DLLHost.exe application that was design specially for this purpose.
  25. What is OLE? OLE is an object and embedding first implementation of COM spec available from MS before COM was officially named COM.
  26. Give examples of OLE usage. The most famous examples are probably drag and drop and structured storage implementations.
  27. What are 2 storage types for composite document? Storage and Stream.
  28. Is .doc document a compound document? Is it a structured storage? Compound document is a document that contains information about other documents hosted in this document. All office documents _may_ be compound documents, but may be not. Word documents from version 6.0 and up are stored as structured storage.

Saturday 30 July 2011

Windows Data Types

Windows Data Types

The data types supported by Windows are used to define function return values, function and message parameters, and structure members. They define the size and meaning of these elements. For more information about the underlying C/C++ data types, see Data Type Ranges.
The following table contains the following types: character, integer, Boolean, pointer, and handle. The character, integer, and Boolean types are common to most C compilers. Most of the pointer-type names begin with a prefix of P or LP. Handles refer to a resource that has been loaded into memory.
For more information about handling 64-bit integers, see Large Integers.
Data typeDescription
APIENTRYThe calling convention for system functions.
This type is declared in WinDef.h as follows:
#define APIENTRY WINAPI
ATOMAn atom. For more information, see Atoms.
This type is declared in WinDef.h as follows:
typedef WORD ATOM;
BOOLA Boolean variable (should be TRUE or FALSE).
This type is declared in WinDef.h as follows:
typedef int BOOL;
BOOLEANA Boolean variable (should be TRUE or FALSE).
This type is declared in WinNT.h as follows:
typedef BYTE BOOLEAN;
BYTEA byte (8 bits).
This type is declared in WinDef.h as follows:
typedef unsigned char BYTE;
CALLBACKThe calling convention for callback functions.
This type is declared in WinDef.h as follows:
#define CALLBACK __stdcall
CALLBACK, WINAPI, and APIENTRY are all used to define functions with the __stdcall calling convention. Most functions in the Windows API are declared using WINAPI. You may wish to use CALLBACK for the callback functions that you implement to help identify the function as a callback function.
CHARAn 8-bit Windows (ANSI) character. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef char CHAR;
COLORREFThe red, green, blue (RGB) color value (32 bits). See COLORREF for information on this type.
This type is declared in WinDef.h as follows:
typedef DWORD COLORREF;
CONSTA variable whose value is to remain constant during execution.
This type is declared in WinDef.h as follows:
#define CONST const
DWORDA 32-bit unsigned integer. The range is 0 through 4294967295 decimal.
This type is declared in WinDef.h as follows:
typedef unsigned long DWORD;
DWORDLONGA 64-bit unsigned integer. The range is 0 through 18446744073709551615 decimal.
This type is declared in WinNT.h as follows:
typedef ULONGLONG DWORDLONG;
DWORD_PTRAn unsigned long type for pointer precision. Use when casting a pointer to a long type to perform pointer arithmetic. (Also commonly used for general 32-bit parameters that have been extended to 64 bits in 64-bit Windows.)
This type is declared in BaseTsd.h as follows:
typedef ULONG_PTR DWORD_PTR;
DWORD32A 32-bit unsigned integer.
This type is declared in BaseTsd.h as follows:
typedef unsigned int DWORD32;
DWORD64A 64-bit unsigned integer.
This type is declared in BaseTsd.h as follows:
typedef unsigned __int64 DWORD64;
FLOATA floating-point variable.
This type is declared in WinDef.h as follows:
typedef float FLOAT;
HACCELA handle to an accelerator table.
This type is declared in WinDef.h as follows:
typedef HANDLE HACCEL;
HALF_PTRHalf the size of a pointer. Use within a structure that contains a pointer and two small fields.
This type is declared in Basetsd.h as follows:
#ifdef _WIN64
typedef int HALF_PTR;
#else
typedef short HALF_PTR;
#endif
HANDLEA handle to an object.
This type is declared in WinNT.h as follows:
typedef PVOID HANDLE;
HBITMAPA handle to a bitmap.
This type is declared in WinDef.h as follows:
typedef HANDLE HBITMAP;
HBRUSHA handle to a brush.
This type is declared in WinDef.h as follows:
typedef HANDLE HBRUSH;
HCOLORSPACEA handle to a color space.
This type is declared in WinDef.h as follows:
typedef HANDLE HCOLORSPACE;
HCONVA handle to a dynamic data exchange (DDE) conversation.
This type is declared in Ddeml.h as follows:
typedef HANDLE HCONV;
HCONVLISTA handle to a DDE conversation list.
This type is declared in Ddeml.h as follows:
typedef HANDLE HCONVLIST;
HCURSORA handle to a cursor.
This type is declared in WinDef.h as follows:
typedef HICON HCURSOR;
HDCA handle to a device context (DC).
This type is declared in WinDef.h as follows:
typedef HANDLE HDC;
HDDEDATAA handle to DDE data.
This type is declared in Ddeml.h as follows:
typedef HANDLE HDDEDATA;
HDESKA handle to a desktop.
This type is declared in WinDef.h as follows:
typedef HANDLE HDESK;
HDROPA handle to an internal drop structure.
This type is declared in ShellApi.h as follows:
typedef HANDLE HDROP;
HDWPA handle to a deferred window position structure.
This type is declared in WinUser.h as follows:
typedef HANDLE HDWP;
HENHMETAFILEA handle to an enhanced metafile.
This type is declared in WinDef.h as follows:
typedef HANDLE HENHMETAFILE;
HFILEA handle to a file opened by OpenFile, not CreateFile.
This type is declared in WinDef.h as follows:
typedef int HFILE;
HFONTA handle to a font.
This type is declared in WinDef.h as follows:
typedef HANDLE HFONT;
HGDIOBJA handle to a GDI object.
This type is declared in WinDef.h as follows:
typedef HANDLE HGDIOBJ;
HGLOBALA handle to a global memory block.
This type is declared in WinDef.h as follows:
typedef HANDLE HGLOBAL;
HHOOKA handle to a hook.
This type is declared in WinDef.h as follows:
typedef HANDLE HHOOK;
HICONA handle to an icon.
This type is declared in WinDef.h as follows:
typedef HANDLE HICON;
HINSTANCEA handle to an instance. This is the base address of the module in memory.
HMODULE and HINSTANCE are the same today, but represented different things in 16-bit Windows.
This type is declared in WinDef.h as follows:
typedef HANDLE HINSTANCE;
HKEYA handle to a registry key.
This type is declared in WinDef.h as follows:
typedef HANDLE HKEY;
HKLAn input locale identifier.
This type is declared in WinDef.h as follows:
typedef HANDLE HKL;
HLOCALA handle to a local memory block.
This type is declared in WinDef.h as follows:
typedef HANDLE HLOCAL;
HMENUA handle to a menu.
This type is declared in WinDef.h as follows:
typedef HANDLE HMENU;
HMETAFILEA handle to a metafile.
This type is declared in WinDef.h as follows:
typedef HANDLE HMETAFILE;
HMODULEA handle to a module. The is the base address of the module in memory.
HMODULE and HINSTANCE are the same in current versions of Windows, but represented different things in 16-bit Windows.
This type is declared in WinDef.h as follows:
typedef HINSTANCE HMODULE;
HMONITORA handle to a display monitor.
This type is declared in WinDef.h as follows:
if(WINVER >= 0x0500) typedef HANDLE HMONITOR;
HPALETTEA handle to a palette.
This type is declared in WinDef.h as follows:
typedef HANDLE HPALETTE;
HPENA handle to a pen.
This type is declared in WinDef.h as follows:
typedef HANDLE HPEN;
HRESULTThe return codes used by COM interfaces. For more information, see Structure of the COM Error Codes. To test an HRESULT value, use the FAILED and SUCCEEDED macros.
This type is declared in WinNT.h as follows:
typedef LONG HRESULT;
HRGNA handle to a region.
This type is declared in WinDef.h as follows:
typedef HANDLE HRGN;
HRSRCA handle to a resource.
This type is declared in WinDef.h as follows:
typedef HANDLE HRSRC;
HSZA handle to a DDE string.
This type is declared in Ddeml.h as follows:
typedef HANDLE HSZ;
HWINSTAA handle to a window station.
This type is declared in WinDef.h as follows:
typedef HANDLE WINSTA;
HWNDA handle to a window.
This type is declared in WinDef.h as follows:
typedef HANDLE HWND;
INTA 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.
This type is declared in WinDef.h as follows:
typedef int INT;
INT_PTRA signed integer type for pointer precision. Use when casting a pointer to an integer to perform pointer arithmetic.
This type is declared in BaseTsd.h as follows:
#if defined(_WIN64) 
typedef __int64 INT_PTR;
#else
typedef int INT_PTR;
#endif
INT32A 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.
This type is declared in BaseTsd.h as follows:
typedef signed int INT32;
INT64A 64-bit signed integer. The range is –9223372036854775808 through 9223372036854775807 decimal.
This type is declared in BaseTsd.h as follows:
typedef signed __int64 INT64;
LANGIDA language identifier. For more information, see Language Identifiers.
This type is declared in WinNT.h as follows:
typedef WORD LANGID;
LCIDA locale identifier. For more information, see Locale Identifiers.
This type is declared in WinNT.h as follows:
typedef DWORD LCID;
LCTYPEA locale information type. For a list, see Locale Information Constants.
This type is declared in WinNls.h as follows:
typedef DWORD LCTYPE;
LGRPIDA language group identifier. For a list, see EnumLanguageGroupLocales.
This type is declared in WinNls.h as follows:
typedef DWORD LGRPID;
LONGA 32-bit signed integer. The range is –2147483648 through 2147483647 decimal.
This type is declared in WinNT.h as follows:
typedef long LONG;
LONGLONGA 64-bit signed integer. The range is –9223372036854775808 through 9223372036854775807 decimal.
This type is declared in WinNT.h as follows:
#if !defined(_M_IX86)
typedef __int64 LONGLONG;
#else
typedef double LONGLONG;
#endif
LONG_PTRA signed long type for pointer precision. Use when casting a pointer to a long to perform pointer arithmetic.
This type is declared in BaseTsd.h as follows:
#if defined(_WIN64)
typedef __int64 LONG_PTR;
#else
typedef long LONG_PTR;
#endif
LONG32A 32-bit signed integer. The range is –2147483648 through 2147483647 decimal.
This type is declared in BaseTsd.h as follows:
typedef signed int LONG32;
LONG64A 64-bit signed integer. The range is –9223372036854775808 through 9223372036854775807 decimal.
This type is declared in BaseTsd.h as follows:
typedef __int64 LONG64;
LPARAMA message parameter.
This type is declared in WinDef.h as follows:
typedef LONG_PTR LPARAM;
LPBOOLA pointer to a BOOL.
This type is declared in WinDef.h as follows:
typedef BOOL far *LPBOOL;
LPBYTEA pointer to a BYTE.
This type is declared in WinDef.h as follows:
typedef BYTE far *LPBYTE;
LPCOLORREFA pointer to a COLORREF value.
This type is declared in WinDef.h as follows:
typedef DWORD *LPCOLORREF;
LPCSTRA pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef __nullterminated CONST CHAR *LPCSTR;
LPCTSTRAn LPCWSTR if UNICODE is defined, an LPCSTR otherwise. For more information, see Windows Data Types for Strings.
This type is declared in WinNT.h as follows:
#ifdef UNICODE
typedef LPCWSTR LPCTSTR;
#else
typedef LPCSTR LPCTSTR;
#endif
LPCVOIDA pointer to a constant of any type.
This type is declared in WinDef.h as follows:
typedef CONST void *LPCVOID;
LPCWSTRA pointer to a constant null-terminated string of 16-bit Unicode characters. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef CONST WCHAR *LPCWSTR;
LPDWORDA pointer to a DWORD.
This type is declared in WinDef.h as follows:
typedef DWORD *LPDWORD;
LPHANDLEA pointer to a HANDLE.
This type is declared in WinDef.h as follows:
typedef HANDLE *LPHANDLE;
LPINTA pointer to an INT.
This type is declared in WinDef.h as follows:
typedef int *LPINT;
LPLONGA pointer to a LONG.
This type is declared in WinDef.h as follows:
typedef long *LPLONG;
LPSTRA pointer to a null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef CHAR *LPSTR;
LPTSTRAn LPWSTR if UNICODE is defined, an LPSTR otherwise. For more information, see Windows Data Types for Strings.
This type is declared in WinNT.h as follows:
#ifdef UNICODE
typedef LPWSTR LPTSTR;
#else
typedef LPSTR LPTSTR;
#endif
LPVOIDA pointer to any type.
This type is declared in WinDef.h as follows:
typedef void *LPVOID;
LPWORDA pointer to a WORD.
This type is declared in WinDef.h as follows:
typedef WORD *LPWORD;
LPWSTRA pointer to a null-terminated string of 16-bit Unicode characters. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef WCHAR *LPWSTR;
LRESULTSigned result of message processing.
This type is declared in WinDef.h as follows:
typedef LONG_PTR LRESULT;
PBOOLA pointer to a BOOL.
This type is declared in WinDef.h as follows:
typedef BOOL *PBOOL;
PBOOLEANA pointer to a BOOLEAN.
This type is declared in WinNT.h as follows:
typedef BOOLEAN *PBOOLEAN;
PBYTEA pointer to a BYTE.
This type is declared in WinDef.h as follows:
typedef BYTE *PBYTE;
PCHARA pointer to a CHAR.
This type is declared in WinNT.h as follows:
typedef CHAR *PCHAR;
PCSTRA pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef CONST CHAR *PCSTR;
PCTSTRA PCWSTR if UNICODE is defined, a PCSTR otherwise. For more information, see Windows Data Types for Strings.
This type is declared in WinNT.h as follows:
#ifdef UNICODE
typedef LPCWSTR PCTSTR;
#else
typedef LPCSTR PCTSTR;
#endif
PCWSTRA pointer to a constant null-terminated string of 16-bit Unicode characters. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef CONST WCHAR *PCWSTR;
PDWORDA pointer to a DWORD.
This type is declared in WinDef.h as follows:
typedef DWORD *PDWORD;
PDWORDLONGA pointer to a DWORDLONG.
This type is declared in WinNT.h as follows:
typedef DWORDLONG *PDWORDLONG;
PDWORD_PTRA pointer to a DWORD_PTR.
This type is declared in BaseTsd.h as follows:
typedef DWORD_PTR *PDWORD_PTR;
PDWORD32A pointer to a DWORD32.
This type is declared in BaseTsd.h as follows:
typedef DWORD32 *PDWORD32;
PDWORD64A pointer to a DWORD64.
This type is declared in BaseTsd.h as follows:
typedef DWORD64 *PDWORD64;
PFLOATA pointer to a FLOAT.
This type is declared in WinDef.h as follows:
typedef FLOAT *PFLOAT;
PHALF_PTRA pointer to a HALF_PTR.
This type is declared in Basetsd.h as follows:
#ifdef _WIN64
typedef HALF_PTR *PHALF_PTR;
#else
typedef HALF_PTR *PHALF_PTR;
#endif
PHANDLEA pointer to a HANDLE.
This type is declared in WinNT.h as follows:
typedef HANDLE *PHANDLE;
PHKEYA pointer to an HKEY.
This type is declared in WinDef.h as follows:
typedef HKEY *PHKEY;
PINTA pointer to an INT.
This type is declared in WinDef.h as follows:
typedef int *PINT;
PINT_PTRA pointer to an INT_PTR.
This type is declared in BaseTsd.h as follows:
typedef INT_PTR *PINT_PTR;
PINT32A pointer to an INT32.
This type is declared in BaseTsd.h as follows:
typedef INT32 *PINT32;
PINT64A pointer to an INT64.
This type is declared in BaseTsd.h as follows:
typedef INT64 *PINT64;
PLCIDA pointer to an LCID.
This type is declared in WinNT.h as follows:
typedef PDWORD PLCID;
PLONGA pointer to a LONG.
This type is declared in WinNT.h as follows:
typedef LONG *PLONG;
PLONGLONGA pointer to a LONGLONG.
This type is declared in WinNT.h as follows:
typedef LONGLONG *PLONGLONG;
PLONG_PTRA pointer to a LONG_PTR.
This type is declared in BaseTsd.h as follows:
typedef LONG_PTR *PLONG_PTR;
PLONG32A pointer to a LONG32.
This type is declared in BaseTsd.h as follows:
typedef LONG32 *PLONG32;
PLONG64A pointer to a LONG64.
This type is declared in BaseTsd.h as follows:
typedef LONG64 *PLONG64;
POINTER_32A 32-bit pointer. On a 32-bit system, this is a native pointer. On a 64-bit system, this is a truncated 64-bit pointer.
This type is declared in BaseTsd.h as follows:
#if defined(_WIN64)
#define POINTER_32 __ptr32
#else
#define POINTER_32
#endif
POINTER_64A 64-bit pointer. On a 64-bit system, this is a native pointer. On a 32-bit system, this is a sign-extended 32-bit pointer.
Note that it is not safe to assume the state of the high pointer bit.
This type is declared in BaseTsd.h as follows:
#if (_MSC_VER >= 1300)
#define POINTER_64 __ptr64
#else
#define POINTER_64
#endif
POINTER_SIGNEDA signed pointer.
This type is declared in BaseTsd.h as follows:
#define POINTER_SIGNED __sptr
POINTER_UNSIGNEDAn unsigned pointer.
This type is declared in BaseTsd.h as follows:
#define POINTER_UNSIGNED __uptr
PSHORTA pointer to a SHORT.
This type is declared in WinNT.h as follows:
typedef SHORT *PSHORT;
PSIZE_TA pointer to a SIZE_T.
This type is declared in BaseTsd.h as follows:
typedef SIZE_T *PSIZE_T;
PSSIZE_TA pointer to a SSIZE_T.
This type is declared in BaseTsd.h as follows:
typedef SSIZE_T *PSSIZE_T;
PSTRA pointer to a null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef CHAR *PSTR;
PTBYTEA pointer to a TBYTE.
This type is declared in WinNT.h as follows:
typedef TBYTE *PTBYTE;
PTCHARA pointer to a TCHAR.
This type is declared in WinNT.h as follows:
typedef TCHAR *PTCHAR;
PTSTRA PWSTR if UNICODE is defined, a PSTR otherwise. For more information, see Windows Data Types for Strings.
This type is declared in WinNT.h as follows:
#ifdef UNICODE
typedef LPWSTR PTSTR;
#else typedef LPSTR PTSTR;
#endif
PUCHARA pointer to a UCHAR.
This type is declared in WinDef.h as follows:
typedef UCHAR *PUCHAR;
PUHALF_PTRA pointer to a UHALF_PTR.
This type is declared in Basetsd.h as follows:
#ifdef _WIN64
typedef UHALF_PTR *PUHALF_PTR;
#else
typedef UHALF_PTR *PUHALF_PTR;
#endif
PUINTA pointer to a UINT.
This type is declared in WinDef.h as follows:
typedef UINT *PUINT;
PUINT_PTRA pointer to a UINT_PTR.
This type is declared in BaseTsd.h as follows:
typedef UINT_PTR *PUINT_PTR;
PUINT32A pointer to a UINT32.
This type is declared in BaseTsd.h as follows:
typedef UINT32 *PUINT32;
PUINT64A pointer to a UINT64.
This type is declared in BaseTsd.h as follows:
typedef UINT64 *PUINT64;
PULONGA pointer to a ULONG.
This type is declared in WinDef.h as follows:
typedef ULONG *PULONG;
PULONGLONGA pointer to a ULONGLONG.
This type is declared in WinDef.h as follows:
typedef ULONGLONG *PULONGLONG;
PULONG_PTRA pointer to a ULONG_PTR.
This type is declared in BaseTsd.h as follows:
typedef ULONG_PTR *PULONG_PTR;
PULONG32A pointer to a ULONG32.
This type is declared in BaseTsd.h as follows:
typedef ULONG32 *PULONG32;
PULONG64A pointer to a ULONG64.
This type is declared in BaseTsd.h as follows:
typedef ULONG64 *PULONG64;
PUSHORTA pointer to a USHORT.
This type is declared in WinDef.h as follows:
typedef USHORT *PUSHORT;
PVOIDA pointer to any type.
This type is declared in WinNT.h as follows:
typedef void *PVOID;
PWCHARA pointer to a WCHAR.
This type is declared in WinNT.h as follows:
typedef WCHAR *PWCHAR;
PWORDA pointer to a WORD.
This type is declared in WinDef.h as follows:
typedef WORD *PWORD;
PWSTRA pointer to a null-terminated string of 16-bit Unicode characters. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef WCHAR *PWSTR;
SC_HANDLEA handle to a service control manager database. For more information, see SCM Handles.
This type is declared in WinSvc.h as follows:
typedef HANDLE SC_HANDLE;
SC_LOCKA lock to a service control manager database. For more information, see SCM Handles.
This type is declared in WinSvc.h as follows:
typedef LPVOID SC_LOCK;
SERVICE_STATUS_HANDLEA handle to a service status value. For more information, see SCM Handles.
This type is declared in WinSvc.h as follows:
typedef HANDLE SERVICE_STATUS_HANDLE;
SHORTA 16-bit integer. The range is –32768 through 32767 decimal.
This type is declared in WinNT.h as follows:
typedef short SHORT;
SIZE_TThe maximum number of bytes to which a pointer can point. Use for a count that must span the full range of a pointer.
This type is declared in BaseTsd.h as follows:
typedef ULONG_PTR SIZE_T;
SSIZE_TA signed version of SIZE_T.
This type is declared in BaseTsd.h as follows:
typedef LONG_PTR SSIZE_T;
TBYTEA WCHAR if UNICODE is defined, a CHAR otherwise.
This type is declared in WinNT.h as follows:
#ifdef UNICODE
typedef WCHAR TBYTE;
#else
typedef unsigned char TBYTE;
#endif
TCHARA WCHAR if UNICODE is defined, a CHAR otherwise.
This type is declared in WinNT.h as follows:
#ifdef UNICODE
typedef WCHAR TCHAR;
#else
typedef char TCHAR;
#endif
UCHARAn unsigned CHAR.
This type is declared in WinDef.h as follows:
typedef unsigned char UCHAR;
UHALF_PTRAn unsigned HALF_PTR. Use within a structure that contains a pointer and two small fields.
This type is declared in Basetsd.h as follows:
#ifdef _WIN64
typedef unsigned int UHALF_PTR;
#else
typedef unsigned short UHALF_PTR;
#endif
UINTAn unsigned INT. The range is 0 through 4294967295 decimal.
This type is declared in WinDef.h as follows:
typedef unsigned int UINT;
UINT_PTRAn unsigned INT_PTR.
This type is declared in BaseTsd.h as follows:
#if defined(_WIN64)
typedef unsigned __int64 UINT_PTR;
#else
typedef unsigned int UINT_PTR;
#endif
UINT32An unsigned INT32. The range is 0 through 4294967295 decimal.
This type is declared in BaseTsd.h as follows:
typedef unsigned int UINT32;
UINT64An unsigned INT64. The range is 0 through 18446744073709551615 decimal.
This type is declared in BaseTsd.h as follows:
typedef usigned __int 64 UINT64;
ULONGAn unsigned LONG. The range is 0 through 4294967295 decimal.
This type is declared in WinDef.h as follows:
typedef unsigned long ULONG;
ULONGLONGA 64-bit unsigned integer. The range is 0 through 18446744073709551615 decimal.
This type is declared in WinNT.h as follows:
#if !defined(_M_IX86)
typedef unsigned __int64 ULONGLONG;
#else
typedef double ULONGLONG;
#endif
ULONG_PTRAn unsigned LONG_PTR.
This type is declared in BaseTsd.h as follows:
#if defined(_WIN64)
typedef unsigned __int64 ULONG_PTR;
#else
typedef unsigned long ULONG_PTR;
#endif
ULONG32An unsigned LONG32. The range is 0 through 4294967295 decimal.
This type is declared in BaseTsd.h as follows:
typedef unsigned int ULONG32;
ULONG64An unsigned LONG64. The range is 0 through 18446744073709551615 decimal.
This type is declared in BaseTsd.h as follows:
typedef unsigned __int64 ULONG64;
UNICODE_STRINGA Unicode string.
This type is declared in Winternl.h as follows:
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING;
typedef UNICODE_STRING *PUNICODE_STRING;
typedef const UNICODE_STRING *PCUNICODE_STRING;
USHORTAn unsigned SHORT. The range is 0 through 65535 decimal.
This type is declared in WinDef.h as follows:
typedef unsigned short USHORT;
USNAn update sequence number (USN).
This type is declared in WinNT.h as follows:
typedef LONGLONG USN;
VOIDAny type.
This type is declared in WinNT.h as follows:
#define VOID void
WCHARA 16-bit Unicode character. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef wchar_t WCHAR;
WINAPIThe calling convention for system functions.
This type is declared in WinDef.h as follows:
#define WINAPI __stdcall
CALLBACK, WINAPI, and APIENTRY are all used to define functions with the __stdcall calling convention. Most functions in the Windows API are declared using WINAPI. You may wish to use CALLBACK for the callback functions that you implement to help identify the function as a callback function.
WORDA 16-bit unsigned integer. The range is 0 through 65535 decimal.
This type is declared in WinDef.h as follows:
typedef unsigned short WORD;
WPARAMA message parameter.
This type is declared in WinDef.h as follows:
typedef UINT_PTR WPARAM;

VC++ Interview Part - 1


Starting point of windows application?
WinMain() is the entry point of Windows applications.
Parameters of WinMain()
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdLine, int nCmdShow)
hInstance – The handle of the currently running module.
hPrevInstance – A handle to a previous instance of the application. For a Win32-based application, this parameter is always NULL.
lpCmdLine – Points to a null-terminated string specifying the command line for the application.
nCmdShow – Specifies how the main window of a GUI application would be shown.
What is windows programming? How it’s working?
Windows is an event driven programming mechanism, in which applications respond to events by processing messages sent by the operating system. An event could be a keystroke, a mouse click, or a command for a window to repaint itself, among other things. The entry point for a Windows program is a function named WinMain, but most of the action takes place in a function known as the window procedure. The window procedure processes messages sent to the window. WinMain creates that window and then enters a message loop, alternately retrieving messages and dispatching them to the window procedure. Messages wait in a message queue until they are retrieved.
Startup of a Simple Windows Program?
LONG WINAPI WndProc (HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdLine, int nCmdShow)
{
WNDCLASS wc;
HWND hwnd;
MSG msg;
//Fill WNDCLASS structure
RegisterClass (&wc);
hwnd = CreateWindow(…);
ShowWindow (hwnd, nCmdShow);
UpdateWindow (hwnd);
while (GetMessage (&msg, NULL, 0, 0)) {
TranslateMessage (&msg);
DispatchMessage (&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
}
What is MFC?
MFC is the C++ class library Microsoft provides to place an object-oriented wrapper around the Windows API. MFC is also an application framework. More than merely a collection of classes, MFC helps define the structure of an application and handles many routine chores on the application’s behalf. Starting with CWinApp, the class that represents the application itself, MFC encapsulates virtually every aspect of a program’s operation. The framework supplies the WinMain function, and WinMain in turn calls the application object’s member functions to make the program go. One of the CWinApp member functions called by WinMain—Run—provides the message loop that pumps messages to the application’s window. The framework also provides abstractions that go above and beyond what the Windows API has to offer.
What is an application framework?
The application framework is a collection of classes and the structure of an application which handles many routine chores on the application’s behalf. The framework also provides abstractions that go above and beyond what the Windows API has to offer.
MFC is an application framework – it acts as object oriented wrapper around the Windows API.
Principle base class in MFC?
CObject is the principal base class for the Microsoft Foundation Class Library. The majority of MFC classes are derived, either directly or indirectly, from CObject.
CObject provides basic services, including
- Serialization support
- Run-time class information
- Object diagnostic output
- Compatibility with collection classes
Difference between ASSERT and VERIFY?
ASSERT evaluates the expression only in the debug version and will throw an exception if the result is 0 and the program termintes.
VERIFY evalutes the expression in Debug and Release version also and if the result is 0, will throw an exception only in Debug mode.
What is the difference between PostMessage and SendMessage?
The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message.
The SendMessage function sends the specified message to a window or windows. It calls the window procedure for the specified window and does not return until the window procedure has processed the message.
What is the difference between PeekMessage and GetMessage?
You can use the PeekMessage function to examine a message queue during a lengthy operation. PeekMessage is similar to the GetMessage function, both check a message queue for a message that matches the filter criteria and then copy the message to an MSG structure. The main difference between the two functions is that GetMessage does not return until a message matching the filter criteria is placed in the queue, whereas PeekMessage returns immediately regardless of whether a message is in the queue.
What is the difference between hInstance and hWnd?
hWnd is the window’s handle and is how the OS defines a window when talking about it inside the PC.
hInstance is the OS’s handle for the program when running it.
What is the difference between Modal and Modeless Dialog?
Modal dialog box captures the message loop, whereas model less does not. Call DoModal to create the dialog window and its controls for a modal dialog. If you wish to create a modeless dialog, call Create in the constructor of your Cdialog class.
Example for Model Dialog is Save, Save As Dialog in MS -Word.
Example for Modeless Dialog is Find,Replace dialogs.
What is the use of CCmdTarget?
It is the base class for the MFC library message map architecture. Which maps commands/messages to the member functions to handle them. Classes derived from this are CWnd,CWinApp,CFrameWnd,CView, CDocument
What is the difference between hinsrtance and hprevinstance in WinMain function?
hInstance : will be having the handle of the current instance
hPrevInctance : will be having the handle of last instance, hPrevInstance is NULL if only one instance is running
Describe the Document/View architecture.
In MFC 1.0, an application had two principal components: an application object representing the application itself and a window object representing the application’s window. The application object’s primary duty was to create a window, and the window in turn processed messages.
MFC 2.0 changed the way Windows applications are written by introducing the document/view architecture. In a document/view application, the application’s data is represented by a document object and views of that data are represented by view objects. Documents and views work together to process the user’s input and draw textual and graphical representations of the resulting data. MFC’s CDocument class is the base class for document objects, and CView is the base class for view objects. The application’s main window, whose behavior is modeled in MFC’s CFrameWnd and CMDIFrameWnd classes, is no longer the focal point for message processing but serves primarily as a container for views, toolbars, status bars, and other user interface objects.
MFC supports two types of document/view applications. Single document interface (SDI) applications support just one open document at a time. Multiple document interface (MDI) applications permit two or more documents to be open concurrently and also support multiple views of a given document
What is document?
In a document/view application, data is stored in a document object. The document object is created when the framework instantiates a class derived from CDocument. It is an abstract representation of a program’s data that draws a clear boundary between how the data is stored and how it is presented to the user. That means the sole purpose of a document object is to manage an application’s data.
What is view?
View objects exist for two purposes: to render visual representations of a document on the screen and to translate the user’s input—particularly mouse and keyboard messages—into commands that operate on the document’s data. Thus, documents and views are tightly interrelated, and information flows between them in both directions.
Distinguish between Window’s OnPaint and View’s OnDraw overridable functions?
Window’s OnPaint function executes corresponding to each WM_PAINT messages. But in the case of document-view architecture when a view receives a WM_PAINT message, it invokes view’s OnDraw function. Actually the framework fields the WM_PAINT message, creates a CPaintDC object, and calls the view’s OnDraw function with a pointer to the CPaintDC object.
The fact that the view doesn’t have to construct its own device context object is a minor convenience. The real reason the framework uses OnDraw is so that the same code can be used for output to a window, for printing, and for print previewing. When a WM_PAINT message arrives, the framework passes the view a pointer to a screen device context so that output will go to the window. When a document is printed, the framework calls the same OnDraw function and passes it a pointer to a printer device context.
What is command routing?
One of the most remarkable features of the document/view architecture is that an application can handle command messages almost anywhere. Command messages is MFC’s term for the WM_COMMAND messages that are generated when items are selected from menus, keyboard accelerators are pressed, and toolbar buttons are clicked. The frame window is the physical recipient of most command messages, but command messages can be handled in the view class, the document class, or even the application class by simply including entries for the messages you want to handle in the class’s message map. The flow of command messages from Active View to DefWindowProc is know as command routine.
ActiveView -> Active View’s Doc -> Document Template -> Frame Window -> Application Object -> DefWindowProc
How Message Map works in an MFC application?
The message map functionality in an MFC application works by the support of 3 Macros, DECLARE_MESSAGE_MAP, BEGIN_MESSAGE_MAP, and END_MESSAGE_MAP and the WindowProc function implementation.
MFC’s DECLARE_MESSAGE_MAP macro adds three members to the class declaration: a private array of AFX_MSGMAP_ENTRY structures named _messageEntries that contains information correlating messages and message handlers; a static AFX_MSGMAP structure named messageMap that contains a pointer to the class’s _messageEntries array and a pointer to the base class’s messageMap structure; and a virtual function named GetMessageMap that returns messageMap’s address. BEGIN_MESSAGE_MAP contains the implementation for the GetMessageMap function and code to initialize the messageMap structure. The macros that appear between BEGIN_MESSAGE_MAP and END_MESSAGE_MAP fill in the _messageEntries array, and END_MESSAGE_MAP marks the end of the array with a NULL entry.
Thus corresponding to each message a class can traverse through it’s and base classes message map entries to find a handler till it to reach the DefWindowProc.
What is the difference between thread and process?
In the Microsoft Win32 environment, every running application constitutes a process and every process contains one or more threads of execution. A thread is a path of execution through a program’s code, plus a set of resources (stack, register state, and so on) assigned by the operating system.

Popular Posts

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | cheap international calls