Sie sind auf Seite 1von 43

1) Explain about VC++?

Microsoft visual C++ helps programmers and developers to create windows and .NET
based applications. This also helps in developing applications for web, windows
based applications, solutions for thin and smart client based mobile devices. I
t is used for developing applications for windows API, .NET framework, etc.
2) Discuss about the stack based buffer over run detection in VC++?
Stack based buffer over run protects the program from executing malicious code.
Function epilogue code checks the returned cookie for similarity if there is a m
ismatch it stops executing the code. It also moves around the stack which makes
the data corruption harder. These features are present in Visual C++ 2005. It al
so mitigates various buffer over runs through memory decrease.
3) What are all the situations where the /GS compiler is not applied.
These are the following situations where /GS compiler is not applied.
1) When functions do not contain a buffer
2) When optimizations is not enabled
3) It is obvious when functions are defined to have a variable argument lis
t it cannot create a static cookie.
4) If functions are marked with a naked keyword such as (C++) etc a GS comp
iler cannot be created.
5) When functions have inline assembly code in the start of the program
6) When a buffer is less than 8 bit type it is not possible and can potenti
ally create a security lapse
4) State some new features which are incorporated into Microsoft visual C++
2008?
Some of the new features which are introduced to VC++ are a large set of new MFC
classes which will certainly help in building modern user interfaces. TR1 is th
e major addition to the pack of VC++. This also has new user interface, adjustab
le panes, and support for Microsoft office ribbon, controls, dialog boxes and wi
ndows.
5) Explain about InitApplication()?
To display an output for a certain application programmers have to use InitAppli
cation() method. InitApplication is a Boolean method. This function outputs a tr
ue if an application gets succeeded. If it did not succeed it displays a false c
ommand. Applications rely on this method to display a certain o/p.
6) Explain about frames?
Frame describes about the borders, dimensions and location of the window. Two ty
pes of MFC applications are present which use a frame. Application using frames
use a concept known as Document/View architecture. This architecture allows a ce
rtain program to be present in applications.
7) Explain about CFrameWnd?
MFC has an extensive set of classes present in its library out of which CFrameWn
d is one of those. This is a very important class and it is used frequently. Use
r defined classes can be created by CFrameWnd. To create a windows frame CFrameW
nd provides class.
8) Explain about CWinThread class?
If you want to provide a window to an application it is imperative to create a t
hread which can be done using CWinThread. A public member variable is used with
CWinThread is m_pMainWnd. The main advantage which you can get when using this t
hread, it terminates the application without any hassles.
9) Name some important features of VC++?
Some of the important features of VC++ are as follows
1) Smart pointers
2) New containers
3) Expression parsing
4) Polymorphic function wrappers
5) Type traits and sophisticated random number generators.
10) Explain about functional?
Functional defines a huge number of templates which help construct function obje
cts which defines operator. Function pointer can be described by a function obje
ct. It stores information which can be accessed during the functional call.
11) Explain about the function regex?
This defines a template to parse certain regular expressions. It also defines se
veral classes and functions to search text that is matching a regular expression
object. There are many declarations, type definitions, template functions, and
operator.
12) Explain about regex_search function?
Regex_search function searches for a regular expression. A true function is retu
rned only when the search in its operand sequence succeeds. It also defines the
various capture groups in the regular expression. Some of the parameters are all
oc, Elem, RXtraits, etc.
13) Explain about tuple in visual c++?
Tuple defines instances of objects in varying types. Declarations, template func
tions and functions are defines in tuples. In class there are three elements the
y are tuple class, tuple size Class and tuple element Class are defined in Visua
l C++.
14) Describe about unordered_map?
Unordered_map defines container template classes such as unordered map and unord
ered multimap template. Under declarations unordered map Class and unordered mul
timap class are defined. These classes store hash table.
15) Explain about type_traits?
Type_traits give information about type arguments and provide compile time const
ants.
Syntax of type_traits is #include
This function is very useful as it helps during the compile time. Specific exten
sions are provided which give useful information as to whether an integral const
ant has a true value or false value.
16) Explain about typedef?
A type predicate takes one or more arguments and it is a template. If a type pre
dicate is true it is publicly derived directly or indirectly from true type def.
In case it is false it is publicly derived from false type def.
17) Explain about utility?
Utility function has several general templates and can be used in Standard templ
ate library. Some of them are tuple element Class which is used to wrap the type
of pair element. Get function is used to get an element from the pair object. T
uple size class wraps the pair element count.
18) Explain about differnt Synchronization Methods?
CMutex - allows only one thread from any process to access an object
CCriticalSection - allows only one thread from within the current process to acc
ess an object
CEvent - notifies an application when an event has occured
CSemaphore - allows between one and a max. number of simultaneous access to an o
bject
19) What types of threads are supported by MFC framework?
MFC supports two types of threads:
1 Worker Thread - Commonly used to handle background task
2 User Interface Thread - Used to handle user inputs and respond to events and m
essages generated by the user
20) What is serialization ?which function is responsible for serializing data ?
erialization is the process of converting an object into sequence of bits so tha
t it can be stored and retrieved from a storage medium e.g. file. serialize() is
responsible for serialization of data
21) What are the types of button controls?
Two types of button controls are there: 1) Command(Push) Button & 2) Radio Butto
n
22) What is LoadLibrary function returns?
On success, LoadLibrary() returns a handle to the module
23) What are the differences between MFC Exception macros and C++ exception keyw
ords?
The major difference between the macros and the keywords is
that code using the macros "automatically" deletes a caught
exception when the exception goes out of scope. Code using
the keywords does not, so you must explicitly delete a
caught exception.
24) How to transfer between one exe to another exe while running in VC++ ?
system("MySecondApplication.exe");
WinExec("MySecondApplication.exe",true);
::ShellExecute(NULL,NULL,L"MySecondApplication.exe",NULL,NULL,NULL);
25) Explain Doc/View architecture ?
Notepad is one real time example of SDI Application.
Document View Architecture :- In this document has two part one is for saving th
e data and one if for displaying the data ( mean to say the view ). This contain
s four classes of MFC.
1) CFrameWnd
2) CView
3) CDocument
4) CWinApp

26) What is LPCTSTR? What does LP denote it?


LPCTSTR = Long Pointer to a Const TCHAR String
27) Does the application have more than one object? If Yes, Briefly explain ?
No,one application can't have more than one object.
Because when we create the Application class object.It
calls WinMain() function & which calls AfxWinInit() to
register the window class, InitInstace() to start,show &
update the window.
Than calls the Run() function which call
CWinThread::MessagePump() for message loop.
Once it receive the WM_QUIT message it will call AfxWinTerm
() to cleanup & exit the application.
So once you create the Application object the Primary
thread will start which is called as UI Thread.
One program can have only one Main function which do all
the above mentioned job.
That's why we can create the one object only.
28) How can we create thread in MFC framework?
AfxBeginThread
29) What is the use of Mutex and critical section ?
Both are the syncronization objects. CMutex is for different process. Where in C
CriticalSection is for with in the process.
30) How to convert a CString variable to char* or LPTSTR?
GetBuffer method of CString function.
31) What is a critical section and how is it implemented?
CCriticalSection is for with in the process.
32) What is the use of OninitDialog ?
OnInitDialog needs to be overridden for initialization of controls ( if any ) of
dialog box.
CDialog m_dlg;
m_dlg.DoModal(); // Here OnInitDialog will get called.
33) How to update all the views whenever document got updated ?
UpdateAllViews - a method of CDocument
34) How is a modal and Modless dialog created?
using Create Method , we can create a Modeless dialog box.
CDialog dlg(IDD_DIALOG1);
dlg.Create();
or
CDialog *newDlg = new CDialog;
newDlg->Create(IDD_DIALOG1,this);
newDlg->ShowWindow(TRUE);
Modal Dialog Box:
CDialog dlg(IDD_DIALOG1);
dlg.DoModal();
35) What is the Size of a class?
1 byte for empty class and also the class contain only declaration size of the c
lass as same as empty class that is 1 byte
Size of the class will be the some of the size of all member variables. For exam
ple if in a class we have one integer and one char. Then in 32 bit OS size will
be 8 bytes ( Padding comes here in picture ).
36) What is the difference between Synchronous sockets and asynchronous sockets?
Asynchronous sockets are usually defined by the server side application and not
by what the client's doing. I'm apparently wrong per your developer, but I thoug
ht an asynchronous socket allows multiple connections by forking or threading. A
synchronous socket processes one request at a time.
37) What is a Message Map?
Message map is the mechanism by which MFC handles the application messages. Adva
ntage of message map over virtual function is in case of virtual function VTABLE
will grow and you will have vptr for each and every instance of your class havi
ng virtual function.
Which will take 4 bytes. So please imgaine if you have more VPTR how much memory
your application will take.
38) What is subclassing?
Subclassing is basically a method that allows you to intercept Windows Messages
that is being sent to a particular Window (ie Form, Control, etc). Windows, by d
efault, are assigned a WinProc when they are instantiated. When a user or the sy
stem interacts with that window, that interaction is in the form of Windows Mess
ages.
You can intercept these messages and include additional handling or replacement
handling.
Even more basically, subclassing allows you to alter the default behavior of a W
indow.
39) DDX (Dialog Data Exchange) and DDV (Dialog Data Validation) are two great to
ols that allow us to easily set and access the values of certain MFC controls. D
DX allows us to link the value of a variable to a control, so that when we initi
alize our dialog box, the value of that variable is assigned to its linked control
. Also, we can just as easily send the value of a control back to that variable.
This is the power of DDX and MFC.
To use some DDX functions, you should override the DoDataExchange function of a
dialog box. The DoDataExchange function handles the allocation of data for each
control, takes one parameter and returns no values:
afx_msg void DoDataExchange(CDataExchange* pDX);
Whenever you override the DoDataExchange function, however, the first line of th
e function should always call the base class version:
CDialog:oDataExchange(pDX);
This allows Windows to complete any housekeeping and assignment duties before yo
ur code is executed. Let s take the EDITTEXT control that we talked about earlier.
By default, its value is empty. We could use the SetWindowText function of the
CEdit class to set its value, however, if we use the DDX_Text function, we can e
liminate the need to manually get the EDITTEXT s value every time we need it. Ther
e are many DDX functions available for all of the different control types. The s
yntax of the DDX_Text function looks like this:
void DDX_Text(CDataExchange* pDX, int nIDC, CString& value);
The first parameter is a pointer-to-CDataExchange value. The CDataExchange* vari
able is provided by Windows when the DoDataExchange function is called. It is ca
lled automatically. The nIDC variable is the numerical Id of the control with wh
ich the data will be shared. Our EDITTEXT control has the id of IDE_NAME, so we
would use that. The last variable is a reference to a CString object, which will
be used to store, and initially retrieve the value of the text box from. A samp
le call to the DDX_Text function from the DoDataExchange function looks like thi
s:
CDialog:oDataExchange(pDX);
CString theName = "John Doe";
DDX_Text(pDX, IDE_NAME, theName);
The code above would automatically set the value contained within our EDITTEXT c
ontrol to John Doe . There s one important thing that happens behind the scenes. Wind
ows automatically calls the UpdateData function, which actually copies the value
from the CString variable to the EDITTEXT control. If we want to set the values
of the controls manually, we can call the UpdateData function at the end of the
DoDataExchange function, passing FALSE to the UpdateData function. On the other
hand, if we want to retrieve the value of the control into our CString variable
, we would pass TRUE to the UpdateData function.
For other controls such as the list box, radio button and check box, we would us
e the similar DDX functions DDX_CBString, DDX_Radio and DDX_Check respectively.
I ll leave you to look at these functions on your own.
Now, onto the DDV functions. Data Dialog Validation functions allow you to let W
indows automatically restrict the values allowed within a control. I will just p
rovide a quick overview of one of the many DDV functions available, again, leavi
ng you to explore the rest on your own.
The DDV_MaxChars function allows us to set the maximum number of characters that
can be entered into an EDITTEXT control. It too should reside in the DoDataExch
ange function, and be called just after any DDX functions. Its syntax looks like
this:
void DDX_MaxChars(CDataExchange* pDX, const CString& value, int nChars);
To set the maximum number of characters for our EDITTEXT control to 20, we would
call DDX_MaxChars like this:
CDialog:oDataExchange(pDX);
theName = "John Doe";
DDX_Text(pDX, IDE_NAME, theName);
DDV_MaxChars(pDX, theName, 20);
To actually return the value from the EDITTEXT control to the CString variable th
eName , we can use the UpdateData(TRUE). This will grab the value contained in the
EDITTEXT control, and spit it into the CString variable, theName . A good place to
call the UpdateData(TRUE) function is just before you use the actual values of
your dialog controls.

40) What function is used to retrieve the currently selected index in a list box
?
GetCurSel is the method.
The document is a Generic Container which is derived from the Document class and
is used to hold the data of the Generic Application
This class takes care of loading the data from any source like the Disk, takes c
are of Updating the data and restoring it back to the Disk source
View derived from CView is the part of the application seen by the user
It shows the ouptut to the user and also takes the Input from the user in the fo
rm of Mouse and Keyboard

There are two types of DV based MFC application


SDI and MDI
SDI stands for Single doument Interface that is this application will have only
one document and One view
MDI stands for Multiple Document Interface that is the application can handle Mu
ltiple documents and Multiple Views
View Represents the client area and the documents data is handled in this class.
Whether SDI or MDI application there is only one Main Frame Window which represe
nts the outermain window of the application
All of the views and documents are contained in this window
The framewindow maintains many tasks for the application such as Minimize, Maxim
ize, Close, Menu for the Main window
When you create an MDI application, you will have CMainFrameWnd which is dervide
d from CFramWnd. In this class there are mainly two methods, OnCreate and PreCre
ateWindow, this is used to change the status Bars, Window Style etc
Whenever an MFC application starts the entry point is always the Application cla
ss. The Application class is derived from CWinApp. The class represents the appl
ication thread and there is only one instance of it running for every program.
Its in the Application class that the document view and framework are set up and
connected together.
The Initinstance method is used to initialize the application before it is avail
able to the users.

********************************************************************************
**************************************
Classes Not Derived from Cobject are
------------------
Simple Value Types
------------------
CFileTime
CFileTimeSpan
CPoint
CRect
CSize
CSimpleStringT
|__CStringT
|_CFixedStringT
CTime
CTimeSpan
---------------
Support Classes
---------------
CCmdUI
|_COleCmdUI
CDaoFieldExchange
CDataExchange
CDBVariant
CFiledExchange
CImage
COccManager
COleDataObject
COleDispatchDriver
CPropExchange
CRecentFileList
CRectTracker
CWaitCursor
-------------------
Internet Server API
--------------------
CHttpArgList
CHtmlStream
CHttpFilter
CHttpFilterContext
CHttpServer
CHttpServerContext
----------------------------
Run-Time Object Model Support
------------------------------
CArchive
CDumpContext
CRuntimeClass
----------
Structures
----------
CCreateContext
CHttpArg
CMemoryState
COleSafArray
CPrintInfo
-------------------------
TypedTemplate Collections
--------------------------
CTypedPtrArray
CTypedPtrList
CTypedPtrMap
-----------------
OLE Type wrappers
-----------------
CFontHolder
CPictureHolder
--------------------
OLE Automation Types
--------------------
COleCurency
COleDateTime
COleDateTimeSpan
COleVariant
----------------
Synchronization
----------------
CMultiLock
CSingleLock
----------
Structures
----------
CCreateContext
CHttpArg
CMemoryState
COleSafArray
CPrintInfo
Classes that are directly derived from CObject are
CCmdTarget
CFile
CDC
********************************************************************************
*************************
CCmdTarget is the base class for Message Map architecture. A message map routes
all the incoming messages to its handler function that you write to handle them'
Key Framework classes that are derived from CCmdTarget are:
CDialog, CDocument, CView, CWnd, CFrameWnd
********************************************************************************
************************
Threads
Thread is a line of execution. Having multiple threads means multiple statments
are executed at the same time.
To write an application for Windows with Threads we need to add the "Windows.h"
header file
The Create() is used to create a thread. In MFC we have the AfxBeginThread membe
r function to create the thread
********************************************************************************
***********************
Command Routing
Command routing is passing the command to command targeted objects until the com
mand is handled. If no command targeted object handles the command, the command
finally reaches the application object which by default reaches the application
object where the command is ignored.
Differnt Scenarios of Command routing:
SDI
CView-> CDocument->CFramewnd ->CWinApp
In MDI
CView->CDocument->CMDIChildWnd->Cframewnd->CWinApp
Q 1. How to get application currently activated, Name of Application and Window
Caption ?
A. [GetForegroundWindow]for getting handle of application which currently have K
eyboard Focus
[GetWindowText] retrieve the Caption Text associated with Windows handle
[GetWindowModuleFileName] return with the path of application!
Q 1.02 How to get drive volume serial number in VC++ ?
A.Either Use [GetVolumeInformation] or see here
http://msdn.microsoft.com/library/default.asp?url= /library/en-us/fileio/fs/enum
erating_mount_points.asp
Q 1.03 How to get the absolute path of the virtual folder like My Doucuments, Re
cycle Bin etc.?
A. Check out the help on [SHGetSpecialFolderPath()] and [SHGetFolderPath()]
Q 1.04 Is there is any wrapper present for the Xml Parser in Visual C++?
A.Maybe you'll find some interesting things http://www.codeproject.com/cpp/#Pars
ers
Q 1.05 How i can change my console display mode to full screen mode in a dos bas
ed c++ program?
A.You will have to use the [SetConsoleWindowInfo] function to set the size. But
before that you have to use functions like [GetConsoleWindow], [GetConsoleScreen
BufferInfo] for the actual effect to take place.
Q 1.06 How do i disable mouse wheel in comboBox (MFC) ?
A. A very nasty trick would be to derive a class from the combobox control, use
it in place of your combobox control, capture the mousewheel messages WM_MOUSEWH
EEL and then don't forward them to the base class...
Q 1.07 How i can run an Application file for a While and then stop it ?
A. use [createprocess()] :- For Creating the Process then call [waitforsingleobj
ect()] for waiting for object to execute and then call [terminateprocess()] to m
ake application terminate.
example class: http://codebeetle.com/page.php?id=31
Q 1.08 Is there an Official C++ rules (perhaps guidelines is better than rules) we
b site?
A. see the http://www.csc.lsu.edu/~kosmas/C++guidelines.pdf
Q 1.09 What is the best was to get the modified date/time of a file ?
A. How about [GetFileAttributesEx()]?
or CFile::GetStatus() or _stat() or GetFileTime()
Q 1.10 How to monitor Directory and Registry for any Modification or Updation?
A. For Monitoring Directory/File changes use [ReadDirectoryChangesW] and for reg
istry monitoring[RegNotifyChangeKeyValue].
Q 1.11 How to Detect Multiple VGA card in Display?
A. Check out [EnumDisplayDevices()].
Q 1.12 How To Make Data Arrival to whole application / or make it global in whol
e application?
A. Make the data global. The simplest thing to do is to place it in stdafx.h, ma
rking the declarations with the extern keyword. In the main program, where you r
etrieve the data from the registry, repeat the declarations without the extern k
eyword.
Q 1.13 Can i normalize this array into 0.0 to 0.1 without precision lost (and st
ill maintain it as float)?
A. No - quite obviously if you compress the numbers into a smaller range, you wi
ll lose precision. Floating point numbers suffer from precision problems anyhow,
you should be using double if you want to improve precision, and a fixed point
format if you want to be absolute lt.
Q 1.14 How to run an application when Computer is about to shutdown?
A. You would need a separate application running that handles the WM_QUERYENDSES
SION message. When that message is received, return 0, start the "dialog based a
pplication." and then shutdown on your own by using ExitWindowEx Api
Q 1.15 How to find Unicode FILENAMES from a certain Directory?
A.Look at [FindFirstFileW()] , [FindNextFileW()] and [FileFindCloseW]
Q 1.16 How can I convert a int to a char*?
A. TCHAR szBuffer[16];
INT iValue = 5;
::wsprintf(szBuffer, TEXT("%d"), iValue);
Method2:
int nNum=10;
char szNum[10];
itoa(nNum,szNum,10);

Q 1.17 How do I add File Version information in project?


A. Just add a Version resource to it. Click on the ResourceView tab in the Works
pace pane. Use Ctrl+R to insert a new resource. Select Version from the list.
(OR) Add a resource file (*.RC) to your project. Add a version information resou
rce to the resource file.
Q 1.18 What the best way to sleep 1 ms?
A.write your own delay routine using high-resolution APIs like [QueryPerformaceC
ounter()] and [QueryPerformaceFrequency()] . you can achieve timer even in micro
seconds.
Q 2.01 How to detect the IE/browser version?
A. look at the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explo
rer\Version I hope this will work.
(OR) just use [GetFileVersionInfo()] and [VerQueryValue()].
Q 2.02 AfxGetAppName() is an MFC function, Is there is any Equivalent Win32 Api?
A.
char szPath[_MAX_PATH], szBase[_MAX_FNAME],
szExt[_MAX_EXT];
GetModuleFileName(NULL, szPath,sizeof(szPath));
_splitpath(szPath, NULL, NULL, szBase, szExt);
(OR) Call GetModuleFileName(), and then PathFindFileName() on the full path.
Q 2.03 How to get Remote IP duirng Socket Connection?
A. use [getpeername] api
Q 2.04 How to Restrict my application to one instance only ?
A. http://flounder.com/nomultiples.htm
http://www.codeproject.com/threads/singleinstancemfc.asp
http://www.codeproject.com/cpp/csingleinst.asp
Q 2.05 How to use nmake?
A.Start by reading http://msdn.microsoft.com/library/default.asp?url=/library/en
-us/vccore/html/ _asug_overview.3a_.nmake_reference.asp
Q 2.06 What is the differences between command.com and cmd.exe?
A.command.com is used for backward compatibility with 16-bit and Windows 9x appl
ications. cmd.exe is not available on either. One obvious difference is how each
handles the space character.
For example, the command md this folder has spaces would fail with command.com b
ut would work with cmd.exe, although four folders would get created. To remedy t
his, the folder name must be surrounded by quotation marks (md "this folder has
spaces").
Q 2.07 How will i use unistd.h in VC++ or what the defination of this header fil
e ?
A.here is it,the Defination of Unistd.h

/* * This file is part of the Mingw32 package.


* * unistd.h maps (roughly) to io.h */
#ifndef _UNISTD_H
#define _UNISTD_H
#include
#include
#endif /* _UNISTD_H */
Just Save it as Unistd.h and Include in your project
Q 2.08 How to dynamically change the coloumn name of a list control?
A. have you tried CListCtrl::SetColumn(.....)?
Q 2.09 Does anyone know a Wrapper class to get samplerate bitrate and time of a
mp3?
A. Here you can find all infos you need: http://www.codeproject.com/audio/MPEGAu
dioInfo.asp
Q 2.10 How can I get the ID of the dialog item which own the focus?
A.Use GetFocus() to find the Ctrl which currently under the Keyboard Focus.Pass
the HWND or CWnd return from call of GetFocus to GetDlgCtrlID which will return
the Numeric ID of Control!
(OR)
What Alok said, with the addition that you can use int id = ::GetWindowLong(::Ge
tFocus(), GWL_ID);
if you'd like to stay win32.
Q 2.11 Is it possible to get info between HWND and Process handle?
A. I need: Get Handle of Main Window from process handle (I know the process han
dle). Get process info (i.e. process ID or handle) from a Window handle (I know
the window handle)?
Answer :- 1. - Use GetProcessId() to get process id from process handle.
Use EnumWindows() to look at each top-level window.
For each top-level window call GetWindowThreadProcessId() to get the thread id a
nd process id that was used to create the window.
Break when you find a top-level window that was created by the specified process
handle/id.
2. - Use GetWindowThreadProcessId() to get the thread id and process id that was
used to create the window.
Q 2.12 How to Include " in a text string without ending the string?
A.BSTR bstRet=SysAllocStringByteLen("Some text with the inch symbol\" and then e
nd",44);
Q 2.13 How to check the string if it is the number ?
A.I believe the function you want is called IsDigit. Here's the MSDN reference.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt
_isdigit.2c_.iswdigit.asp
(OR)
The old fashioned way was to use strtoul and check the 'end pointer'. But be awa
re if it is a very large number it will fail with an overflow
(OR)
Use strtod instead of atof. It has a parameter that points to first character in
the string that it does not recognize as part of a number. If that character is
not NULL (the end of the string) the string is not a number. It takes into acco
unt your current locale settings and exponential numbers.
Q 2.14 How to change attributes for a directory?
A. if (! SetFileAttributes("c:\\ResOrg",FILE_ATTRIBUTE_READONLY))
{
DWORD dwError = GetLastError();
}
Q 2.15 How can i find out through code, the amout of processing power my applica
tion is using ?
A.http://www.codeproject.com/threads/getprocesstimes.asp?df=100&forumid=15846&se
lect=799345#xx799345xx
Q 2.16 How can i find out the information about my computers processor like - Ma
nufacturer, Clock Speed etc?
A. Try the Win32_Processor WMI class.
Q 2.17 Has anyone seen code that finds mersenne prime numbers?
A.Google for the GIMPS project. I was going to refer you to the Mersenne site bu
t it is currently down.
(OR) http://www.mersenne.org/
http://www.mersenne.org/source.htm
Q 2.18 how I can convert a DWORD (32 bits) value into a byte array of four bytes
(32 bits)?
A. for (int i = 3; i >= 0; --i)
{
length[3 - i] = (dwLength & (0xff <<(i * 8))) >> (i * 8);}
(OR)
DWORD dwLength=(DWORD) file.GetLength();
BYTE length[sizeof(DWORD)];
*(DWORD*) &length[0] = dwLength;

(OR)
length[0]=HIBYTE(HIWORD(dwLength));
length[1]=LOBYTE(HIWORD(dwLength));
length[2]=HIBYTE(LOWORD(dwLength));
length[3]=LOBYTE(LOWORD(dwLength));
Q 2.19 How to start at Program which start Hidden on Windows startup but Visible
other wise?
A. I Believe you starting you Application at windows startup using key stored in
Registry location RUN. Now to distinguish wheather the User is Starting the Pro
gram by Clicking over it or Windows is Starting it at start up, you just provide
a command line argument to that reg Location i.e. store application path as
c:\\your_app_path\\app.exe -hidden
Now When ever Windows start your application at startup offcourse, you will get
-hidden as commandline argument, now you just have to parse the command line [us
e GetCommandLine() : to retrieve command line arguments]to hide or unhide your a
pplication.
Q 2.20 What is this Error : "error C2664: 'TextOutW' : cannot convert parameter
4 from 'char [10]' to 'const unsigned short *'"?
A. Sounds like the dll is being compiled with a UNICODE configuration. Enclose y
our string with TEXT() or _T("") and it should work. This will use the appropria
te string type (char or wchar_t) for this function.
Q 2.21 How to Apply Xp Style to the Application ?
A. http://www.codeproject.com/dotnet/ManifestInjection.asp
http://www.codeproject.com/w2k/makexp.asp
http://www.codeproject.com/useritems/ManifestMacro.asp
http://www.codeproject.com/cpp/xpstylemfc.as
Q 3.01 How to determine if IE has finish loading?
A. Kharfax Quoted :-
You should create a browser helper object (Search BHO in Google) and handle the
DOCUMENT_COMPLETE event.
Q 3.02 how to update edit control text ?
A. If m_edit is a control (not data) member (i.e. m_edit is of type CEdit),
do the following: m_edit.SetWindowText ("Test");
to set the edit control's text.
(OR)
Use: DDX_Text(pDX, IDC_EDIT1, m_edit);
and after assigning the values use:
m_edit = "Test";
UpdateData( false );
Q 3.03 How to get output of console program?
A. http://support.microsoft.com/default.aspx?scid=kb;en-us;190351
http://msdn.microsoft.com/library/en-us/dllproc/base/creating_a_child_process_wi
th_redirected_input_and_output.asp
Q 3.04 How to add a progress bar in status bar using Win32 Api ?
A.1. Create status bar w/panes
2. Get rect of pane that progress ctrl will be placed in using SB_GETRECT
3. Create progress control using status bar as parent, and rect value returned i
n (2) to set its position.
4. Manipulate progress ctrl as desired.
Q 3.05 How to set background image for a dialog in MFC ?
A. Does this help? http://www.codeproject.com/dialog/bmpdlg01.asp
Q 3.06 How to detect if an internet connection is available?
A. this MS resource will help you http://www.pcausa.com/resources/InetActive.txt
(OR)
You'd think it'd be really easy but it ain't Check out this
http://ewbi.blogs.com/develops/2003/12/wmi_and_network.html
for more info.
Q 3.07 How to Connect with website and Save Html Page in File ?
A.this article will help you in retrieving HTML pages form Internet server/Domai
n http://www.codeproject.com/internet/amhttputils.asp
(OR)
you can use Ander's AmHttpUtilities class.
Q 3.08 How can you retrieve the HINSTANCE when you only have HWND ?
A.To get hInstance. you can use AfxGetWinApp() sdk function. It retrives hInstan
ce of the application.
(OR)
Use GetWindowLong() with the GWL_HINSTANCE flag.
Q 3.09 How to Set root Folder in CFileDialog?
A. CFileDialog has a member m_ofn, which is an OPENFILENAME structure. In that s
tructure, you have to set the lpstrInitialDir variable to point to a string cont
aing the folder in question.
CFileDialog FileDialog(TRUE);
FileDialog.m_ofn.lpstrInitialDir ="C:\\MyDirectory";
FileDialog.DoModal();
Q 3.10 How to get list of computers in specified workgroup?
A.NetGroupGetUsers()?
Q 3.11 How to get the PhysicalDrive number which the logical drive located?
A.If you need that to do something like send IOCTLs (DeviceIoControl), you can a
lso open the device by using the following syntax:
\\.\C: - Open physical device for drive "C"
\\.\D: - Open physical device for drive "D"
\\.\A: - Open physical device for drive "A"
I do not know all of the cases where that format and the
\\.\PhysicalDrivex format are interchangable,but I know you can use it when
getting a HANDLE to use with DeviceIoControl.
Also, not that you are likely to hit it, but there is a bug in older versions
of the Win32_DiskDrive WMI class that limits the number of drives returned. The
above method should also work on Windows NT 4.0 versions prior to SP4, but the
WMI method will not.
Q 3.12 How to programatically change the 'Work Offline' state to the normal 'Onl
ine' state?
A. Check is this api [InternetGoOnline] help If DialUp you can use these api's t
oo [InternetAutodial] and [Internetdial]
(OR)
I would look into InternetCheckConnection(...), it has a flag that forces connec
tion; and InternetAttemptConnect(...).
Q 3.13 How to find the way to obtain the user names (or user id's) of the owners
of process ?
A. Have a look at the PSAPI and Tool Help Library in MSDN.
(OR) Try This... http://codebeetle.com/page.php?al=process_username
Q 3.14 How to catch that user clicked 'x' button ?
A.Handle WM_SYSCOMMAND and check for the case SC_CLOSE.
Q 3.15 How To Launch email client with attachment ?
A.I do not think that you can, you may have to use MAPI (look up "Simple MAPI" i
n MSDN).
Q 3.16 How can I change the foreground color of an edit control?
A.handle WM_CTLCOLOR message and call SetTextColor() on the supplied DC.
Q 3.17 Is there a way of determining which OS running?
A. Is there a way of determinig the OS running?
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/os
versioninfo_str.asp
But if you use unsupported API's, then you need to dynamically load them, or you
r app won't run, even if you never run the code that calls them. The alternative
is to write your own versions. Do that with TransparentBlt and AlphaBlend
How many different windows platforms are there?
Assuming you start with W95, there's W95, W98, NT4, WME, W2000, WXP. Then W98 ha
s service pack 2 to consider, that added a lot, from memory.
Q 3.18 How to get notified when user logoff?
A. Check out ISensLogon Interface.
Q 3.19 How can I find out how much memory (Private Bytes) my app currently has ?
A. You can use the performance counters for this. Something like:
TCHAR szAvailBytes[256] = TEXT("");
TCHAR szCacheBytes[256] = TEXT("");
TCHAR szWorkingSet[256] = TEXT("");
TCHAR szBuffer[256] = TEXT("");
DWORD dwBufferSize = sizeof(szAvailBytes);
HCOUNTER hAvailBytes, hCacheBytes, hWorkingSet;
HQUERY hQuery = NULL;
PDH_COUNTER_PATH_ELEMENTS pdhCpe;
PDH_STATUS pdhStatus;
PDH_FMT_COUNTERVALUE pdhfmtAvail, pdhfmtCache, pdhfmtWorking;
pdhStatus = PdhOpenQuery(NULL, 0, &hQuery);
if (pdhStatus == ERROR_SUCCESS)
{
// Make Counter Path
pdhCpe.szMachineName = TEXT("crow-nt");
pdhCpe.szObjectName = TEXT("Memory");
pdhCpe.szInstanceName = NULL;
pdhCpe.szParentInstance = NULL;
pdhCpe.dwInstanceIndex = -1;
pdhCpe.szCounterName = TEXT("Available Bytes");
pdhStatus = PdhMakeCounterPath(&pdhCpe, szAvailBytes, &dwBufferSize, 0);
pdhCpe.szCounterName = TEXT("Cache Bytes");
dwBufferSize = sizeof(szCacheBytes);
pdhStatus = PdhMakeCounterPath(&pdhCpe, szCacheBytes,&dwBufferSize, 0);
pdhCpe.szObjectName = TEXT("Process");
pdhCpe.szInstanceName = TEXT("_Total");
pdhCpe.szCounterName = TEXT("Working Set");
dwBufferSize = sizeof(szWorkingSet);
pdhStatus = PdhMakeCounterPath(&pdhCpe, szWorkingSet, &dwBufferSize, 0);
// Add counters.

pdhStatus = PdhAddCounter(hQuery, szAvailBytes, 0, &hAvailBytes);


pdhStatus = PdhAddCounter(hQuery, szCacheBytes, 0, &hCacheBytes);
pdhStatus = PdhAddCounter(hQuery, szWorkingSet, 0, &hWorkingSet);
// Get the data.
pdhStatus = PdhCollectQueryData(hQuery);
// Format counter values.
pdhStatus = PdhGetFormattedCounterValue(hAvailBytes, PDH_FMT_LONG | PDH_FMT_NOSC
ALE, NULL,
&pdhfmtAvail);
pdhStatus = PdhGetFormattedCounterValue(hCacheBytes,PDH_FMT_LONG | PDH_FMT_NOSCA
LE, NULL, &pdhfmtCache);
pdhStatus = PdhGetFormattedCounterValue(hWorkingSet, PDH_FMT_LONG | PDH_FMT_NOSC
ALE, NULL,
&pdhfmtWorking);
wsprintf(szBuffer, TEXT("Physical Mem = %ldMB\n"),
(pdhfmtAvail.longValue + pdhfmtCache.longValue + pdhfmtWorking.longValue) / (102
4 * 1024));
pdhStatus = PdhCloseQuery(hQuery);}
Q 3.20 How can i want to detect whether certain path or directory exists or not?
A.Dude, you need to go here first:
http://www.codeproject.com/cpp/cppforumfaq.asp[^]
if( (DWORD)-1 == GetFileAttributes(szFilePath) ){ tells you if it is missing }
(OR)
//! Checks whether a directory exists.
//! @param strDirectory Directory
//! @return true if the directory exists, false otherwise.
bool dirExists (CString strDirectory)
{
// Create full directory specification - return if unable

TCHAR* fullPath = _tfullpath (NULL,strDirectory, 0);


if (fullPath == NULL)
return (false);
// Check if directory exists by trying to make it the default directory
TCHAR szCurrDir [_MAX_PATH];
_tgetcwd (szCurrDir, _MAX_PATH - 1);
long nStatus = _tchdir (fullPath);
_tchdir (szCurrDir);
// Return free (fullPath);
if (nStatus == 0) return (true); return (false);
}
(OR)
Try [PathFileExists] api
Q 3.21 How to refresh Explorer window after Registry key changed?
A. Check out [SHChangeNotify()] - there might be a flag that will make Explorer
refresh its views.
Q 3.22 How can I determine the height in pixels of status bars?
A. Get the window handle to the status bar's window. Then can call GetWindowRect
. Take the height of the rectangle as the height of the status bar.
Q 3.23 How do you duplicate a file?
A.Try CopyFile or CopyFileEx here is the description:
BOOL CopyFile
( LPCTSTR lpExistingFileName,
LPCTSTR lpNewFileName,
BOOL bFailIfExists
);
(OR)
Also look at the MakeSureDirectoryPathExists function if you need to copy the fi
le to a specific folder hierarchy. (This function is in the dbghelp.dll, which y
ou'll need to distribute depending on the target OS -
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/make
suredirectorypathexists.asp
Q 3.24 How to rotate a GDI object in VC++ without using setworldtransform?
A. If it's a DIBSection( i.e. you have access to the bitmap bits ), then you can
perform the rotate yourself on a new DIBSection ( seeing as a rotated image is
bigger).
Q 3.25 What is #pragma pack()?
A.Perhaps a simple example is better than any explanation.
First case:
#pragma pack(1)
struct MyStruct
{
BYTE a;
UINT b;
};
#pragma pack()
sizeof(struct MyStruct) will return 5 bytes (1+4=5)
Second case:
#pragma pack(4)
struct MyStruct
{
BYTE a;
UINT b;
};
#pragma pack()
sizeof(struct MyStruct) will now return 8 bytes! (1+3+4=8) because the compiler
aligns each member of MyStruct to a 4 bytes boundary. Concretly, the directive t
ells the compiler that the address of each member must be divisible by 4. To do
that, the compiler insert the necessary blank bytes between variable members.

Q 4.01 How to get these parameter like HDD id, Motherboard ID, CDROM-Drive id wi
thout using Registry and MFC ?
A. This from the msdn http://msdn.microsoft.com/library/default.asp?url=/library
/en-us/wmisdk/wmi/computer_system_hardware_classes.asp
Q 4.02 How to get notified that the screensaver has become active?
A.When a screen saver starts, it posts a WM_SYSCOMMAND message to the foreground
window with wParam equal to SC_SCREENSAVE.
Q 4.03 How to access the variables declared in Doc.h from another .cpp?
A. http://support.microsoft.com/default.aspx?scid=kb;en-us;108587
Q 4.04 How to get all avaliable time zone?
A.These Api will help:-
EnumTimeFormats
EnumDateFormats
EnumCalendarInfo
EnumUILanguages
Q 4.05 How i can set the text of the buttons in the toolBar ?
A. Send a TB_SETBUTTONINFO message to the toolbar.
(OR) SetWindowText(HANDLE_OF_BUTTON, BUTTON_TEXT);
Q 4.06 How to get the main icon of an EXE and then change the main icon of anoth
er EXE with that one?
A. Do you mean by actually modifying the .exe file? If so, check out BeginUpdate
Resource() and UpdateResource(..., RT_ICON, ...).
Q 4.07 How to make sure someone is logged on to the computer ?
A. How about NetWkstaUserGetInfo()?
CodeBeetle Quoted :-
if u use OpenInputDesktop() and it returns NULL then the interactive desktop is
not available. ie: no-one is currently logged on or "using" the computer
Q 4.08 How can i access the mapped network drive?
A. Once you have mapped a drive letter to a network resource, the functions that
use said drive letter are none the wiser.
For example:
FindFirstFile("c:\\*.*", ...);
FindFirstFile("n:\\*.*", ...);

operate in the same fashion. Now if you are asking how to establish a connection
between
your computer and a remote computer, simply use NetUseAdd() or WNetAddConnection
2().
Q 4.09 I have programmed my Application using the Visual C++ 6.0, how could i be
sure which version of MFCxx.dll i have supply with application?
A. Have a look at this http://msdn.microsoft.com/library/default.asp?url=/librar
y/en-us/vccore/html/vcconmfcvisualcversionnumbers.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvc60/html/red
istribvc6.asp
(OR)
Start your application with Depends.Exe. This tool will show you which DLLs are
used by your program. It can be found in a sub directory of Visual.
Q 4.10 What is the difference between an accelerators and a hotkey?
A.People use the two names interchangably.
Hot Key is a common user name for an accelerator. Being pedantic... An accelerat
or is a part of an accelerator table. (LoadAccelerator, TranslateAccelerator, et
c.) It only works when your application has the keyboard focus.
A Hot Key is a a system wide key (RegisterHotKey, UnregisterHotKey). When presse
d, windows send a WM_HOTKEY message to you. It works all the time. You could use
it to make a certain key combination do something even when your application is
hidden. (eg. screen capture, etc).
I would not recommend having it active all the time, as it may collide with acce
lerators of other applications.
(OR)
Some also confuse one or both of those words with a "mnemonic", which is the und
erlined character you get on dialog controls allowing you to focus or activate t
hat control using the key along with the key of the underlined character. They (
mnemonics) are also used on top-level Menus and Menu Items (although you do not
need to use the key when a menu or menubar is active).
Q 4.11 How to take the real part from a decimal number for example if i have 3.1
3 take only the 3 ?
A. #include
int nFloor = (int)floor(3.13);
(OR)
Try:
double d = 3.13;
int n = d;
(OR)
From MSDN: double modf( double x, double *intptr );
Splits a floating-point value into fractional and integer parts. This function r
eturns the signed fractional portion of x. There is no error return.
x : Floating-point value. intptr : Pointer to stored integer portion. The modf f
unction breaks down the floating-point value x into fractional and integer parts
, each of which has the same sign as x. The signed fractional portion of x is re
turned. The integer portion is stored as a floating-point value at intptr.
Q 4.12 How to find out if my mouse position is on a specific line ?
A.I used this article to hit test a line: Win32: Hit Testing Lines and Curves at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dngdi/html/msd
n_hittest2.asp
Q 4.13 How to get the TYPE of control?
A. Use GetDlgItem to get the window handle/object. Use GetClassName to retrieve
the class name /type of.
Q 4.14 How to set timeout value in programm using csocket class ?
A. [SetSocketOpt]
Q 4.15 Is there a way/method to modify the current date value so that it will en
d up become the last day of the next month in c runtime library?
A.For that,You have to derive your own LOGIC. here is small piece of code to get
started.
// Get current date
time time_t tDateTime;
struct tm *pstTM,endDate;
int isLeap;
time(&tDateTime);// Convert to tm structure pstTM=
localtime(&tDateTime);
printf("\nToday-%d/%d/%d",pstTM->tm_mday,pstTM->tm_mon+1,pstTM->tm_year+1900);
//Check is Year is Leap?
if(pstTM->tm_year%4) isLeap=1; else isLeap=0;
endDate=*pstTM;
//Now start putting Modified date
// Check for February
if(endDate.tm_mon==1)
{
if(isLeap)
endDate.tm_mday=29;
else
endDate.tm_mday=28;
}
else
{
//Now For 31 days Month
if(((!(pstTM->tm_mon%2))&&(pstTM->tm_mon<=6))
||((pstTM->tm_mon%2))&&(pstTM->tm_mon>=7))
endDate.tm_mday=31;
else
//for Thirty Day Month
endDate.tm_mday=30;
}
printf("\nModified Date: %d/%d/%d" ,endDate.tm_mday,endDate.tm_mon+1,endDate.tm_
year+1900);
(OR)
If you are into Boost then I suggest you use boost:date which uses ISO 8601. See
: http://www.boost.org/doc/html/date_time.html and http://www.cl.cam.ac.uk/~mgk2
5/iso-time.html
(OR)
difftime could be very useful when you want to jump from one time period to anot
her. I used to use it a lot when I was writing software for room bookings.
Q 4.16 How to establish the Window Dial up connection programmatically?
A.http://msdn.microsoft.com/library/en-us/wininet/wininet/establishing_a_dial_up
_connection_to_the_internet.asp
Q 4.17 How to crop an image in an application based on dialog?
A.The obvious thing to do is to create a new bitmap and use BitBlt to copy just
the bit you need. The box part is easy, just draw the box at the mouse position,
and keep track of the position in onmousemove.
Q 4.18 How to load the Dll function which argument can only known at runtime ?
A.Check out "Smashing the Stack for fun and profit" by Aleph One. great docu for
understanding stack manipulation with lots of codes snippets . http://www.phrac
k.org/phrack/49/P49-14.hi
Q 5.01 How to remove close button from window?
A.I don't think that there is an easy way to remove the close button, since it's
part of the system menu. You can use GetSystemMenu() to disable it..
You can also remove the entire title bar. But please tell me why you want to rem
ove the close button? Users will be really annoyed by this! .
(OR)
Try this: GetSystemMenu(FALSE)->EnableMenuItem(SC_CLOSE, FALSE);
Q 5.02 How to change foreground and back ground color of Edit Control?
A. Check these api's [SetTextColor],[SetBkColor]
Q 5.03 What is the structure of .RC file ?
A. RC Compiler Syntax:- http://msdn.microsoft.com/library/default.asp?url=/libra
ry/en-us/tools/tools/resource_definition_statements.asp
Q 5.04 How to create a pop up message near the right hand corner of the task bar
?
A. I know I've seen articles here on that subject, search for "(taskbar OR tray)
notification window" or something like that. (BTW, MS calls that style of popup
"toast", like toast popping up from the toaster. )
(OR)
maybe this will help you:- http://www.codeproject.com/dialog/taskbarnotifier.asp
Q 5.05 how to make setup in visual c++ ?
A. FreeWare Setup Maker!
http://www.jrsoftware.org/isinfo.php
or if you looking for sourcecode:-
http://www.codeproject.com/tips/installbuilder.asp
http://www.codeproject.com/tools/EasyInstaller.asp
Q 5.06 How to convert text file to BMP on runtime?
A. Load (or create) the bitmap, select it into a memory DC and use DrawText or T
extOut to draw your text onto the bitmap the same as you would draw text onto th
e screen DC. Select the bitmap out of the DC and save it.
Q 5.07 How can I get the default printer which is connected on a pc directly or
on a LAN?
A.Have a look at CWinApp::GetPrinterDeviceDefaults()
(OR)
Check out for EnumPrinters API, This should be able to get you available printer
s.
Q 5.08 How to change the HTML currently loaded in IE, programmatically?
A. This link will help:- http://msdn.microsoft.com/library/en-us/dnwebgen/html/b
ho.asp
Q 5.09 How to use database created in MS Access 2000 in pc where MS Access in no
t Installed?
A. Sadly you can't. Access forms require MS Access to be installed (or at least
the Access Runtime). If you have the correct licencing you can redistribute the
MS Access runtime.
Q 5.10 What's the SDK function of the DeflateRect of MFC?
A. There is no corresponding function in the SDK. Actually, if you look at the d
efinition of CRect::DeflateRect, you will see that it calls ::InflateRect by neg
ating the parameters.
(OR)
No SDK available for that, you have to implement that. here is small logic to pr
oceed :-
void MyDeflate(RECT *rect,int left,int top,int right,int bottom)
{
rect->bottom-=bottom;
rect->right-=right;
rect->top+=top;
rect->left+=left;
}
void MyDeflate(RECT *rect,SIZE size)
{
MyDeflate(rect,size.cx,size.cy);
}
void MyDeflate(RECT *rect,int x, int y)
{
MyDeflate(rect,x,x,y,y);
}

Q 5.11 If I add 100 to current date, how to get that modified date ?
A. Let Today is "2005-6-2", if I add 100 days to it Something like:
CTime Time(2005,6,2,0,0,0); // Look in the doc for the "daylight savings time"
// that you want to use
CTimeSpan Span(100,0,0,0);
CTime NewTime = Time + Span; // NewTime will hold the time you are looking for
Q 5.12 How to send the Image File over the Socket ?
A.CSocketFile may do the job, like reading and writing files at either end.
(OR)
If you are using RAW SOCKET, read whole image file in the STRING and then send i
t over the connected socket to other END. this really work!,One of My project us
ing similiar logic!
Q 5.13 How my service can impersonate Administrator (the service has access to t
he login information) while interacting with the Service Manager?
A.Any information...
Call LogonUser to get token handle.
Call ImpersonateLoggedOnUser using the token handle.
...Do your special stuff...
Call RevertToSelf to go back to your original identity.
Q 5.14 Is there an SDK func that can convert big buffers from big endian to litt
le endian ?
A.I don't know of a SDK to do it, but switching endian's isn't a big deal. You c
an do the following:
typedef struct _tagByteBreak
{
unsigned char bUpperByte;
unsigned char bMiddleByte1;
unsigned char bMiddleByte2;
unsigned char bLowerByte;
} BYTE_BREAK;

typedef union _tagEndianSwitch


{
BYTE_BREAK stBreak;
unsigned long int ulFull;
} ENDIAN_SWITCH;
void UTIL_SwitchEndian (unsigned long int *pulIn)
{
ENDIAN_SWITCH Endian;
unsigned char btemp;
Endian.ulFull = *pulIn;
btemp = Endian.stBreak.bLowerByte;
Endian.stBreak.bLowerByte = Endian.stBreak.bUpperByte;
Endian.stBreak.bUpperByte = btemp;
btemp = Endian.stBreak.bMiddleByte1;
Endian.stBreak.bMiddleByte1 = Endian.stBreak.bMiddleByte2;
Endian.stBreak.bMiddleByte2 = btemp;
*pulIn = Endian.ulFull;
}
This code takes a unsigned long int (32-bits) at swops the endian (either direct
ion). Now all you need is a loop:
void ConvertEndian (unsigned long int szLen, unsigned long int *pulBuf)
{
for (unsigned long int i = 0; i < szLen; ++i)
{
UTIL_SwitchEndian (&pulBuf[i]);
}
}

This will convert the buffer to the opposite endian system. It should be easy to
modify for 16-bits.
Q 5.15 How to convert the Hexadecimal into Binary?
A. RichardS Quoted :-
ow do you want to store the binary? So you want a string that reads "0110 1111 1
100 1001"? or is it in a 16-bit variable? As for swapping the bytes, store the b
ytes in array achOrig,
then just bit shift them: s
hort int w16Bits = (achOrig[0] << 8) | achOrig[1];
Now you will have w16Bits = 6F C9 (in memory)
Q 5.16 How programatically examine what text in clipboard?
A. See this CP article and this MSDN article.
Q 5.17 How to programmatically know that Webcam is attached to USB port?
A.If the webcam has a valid driver installed you just need to enumerate connecte
d video devices and look for a "friendlyname" that matches that of your webcam.
Look at AMCAP source code (in the DirectShow SDK samples) for details of how to
do that. AMCAP enumerates all connected video devices and lists their "friendlyn
ame"s in a menu from which the user can select one.
Q 5.18 How to Send Email from my program without having email account?
A. Sure it is possible. There are two ways of sendinig an EMail:
1. use a relay server if you chose this option you you need a SMTP server that d
oes not need authentication. You can use the SMTP-Server that is part of Microso
ft's IIS.
2. Send directly to the recipient Just do a MX DNS lookup on the email adress an
d then send post the mail directly to the recipients mailserver using SMTP over
port 25. Then you need to create a mime message for the mail you'd like to send.
(see rfc 822 for this). Then you need to deliver the mail.
Again two options:
1. if you use the IIS's SMTP server (or any other server that supports a drop di
rectory) you can simply save you message to the mailserver's drop directory (C:\
Inetpub\smptroot\pickup). The SMTP server will queue the mail and send it to the
recipient.
2. open a connection on port 25 to the recpients mail server, send HELO etc... A
n answer for the implementation details of MIME mails and the SMTP protocol woul
d exceed the frame of the forum by far.
But as far as i remember there are good articles on both issues like http://www.
codeproject.com/tips/CSMTPConnection2.asp
Q 5.19 How to send Data/UDT thorugh Window Message?
A.When you send the message, cast the values to WPARAM and LPARAM and then cast
them back in the message handler:
// sending
TCHAR* pszValue = _T("abc");
int iValue = 42;
SendMessage(hwnd, MY_WM_MESSAGE1, (WPARAM)pszValue,(LPARAM)iValue);
// receiving LONG CYourClass::OnMessage1(WPARAM wp, LPARAM lp)
{
TCHAR* psz = (TCHAR*)wp;
int i = (int) lp;
}
(OR)
CString* pString = new CString(_T("Text"));
int nNumber = 100;
PostMessage(hMyWnd, MY_WM_MESSAGE1, reinterpret_cast(pString),
reinterpret_cast(nNumber));
The string must be allocated on the heap, otherwise it will bomb on you when it
goes out of scope. You'll need to free the memory for it when the OnMyMessage1 i
s received. in OnMyMessage1...
CString* pString = reinterpret_cast(wParam);
int nNumber = reinterpret_cast(lParam);
...delete pString;
(OR)Yes, as other have just suggested you may cast your int and string to wparam
and lparam repectively. But what are you going to do if you will need to pass m
ore data than do not fit in two variables later? I'd suggest to declare a struct
, that would contain any information you need to pass with a message. This has o
ne long tern advantage - if the code to be tweaked sometime later, tweaking will
not affect function signatures and the app's architecture.
struct MYMESSAGEDATA
{
int nInteger;
char* nString; // add here anything you want later
// e.g. status flags, length of a string, etc.
}; ... ... MYMESSAGEDATA*
pData = new MYMESSAGEDATA;
pData->nInteger = 1;
pData->nString = "string";
... ... ::SendMessage(hwnd, msg, NULL, (WPARAM)pData);
... LRESULT CProvaDlg::OnMyMessage1(WPARAM wParam, LPARAM lParam)
{ // cast lprama back to our message data
MYMESSAGEDATA* pIncomingData = (MYMESSAGEDATA*)lParam;
//do what ever you need ... ...
//deallocate memory
delete pIncomingData;
return 0;
}
As you can see in above example, you have a spare wParam which could be used to
pass, for example, ID of the sender of the message, consider it as another advan
tage of this approach.
Q 5.20 How to get the number of bytes/packets being received / sent over an NIC
(standard ethernet card)?
A. Either look for IPHelper Apis or http://www.winpcap.org/
(OR)
You can also use WMI (Windows Management Intruments) objects for this monitoring
. It provides all the features, in terms of objects. It is very is use and work.
. Please check with MSDN with Win32_NetworkAdapterConfiguration section. IT will
help you a lot..
Q 5.21 Could anybody refer me to RAW DATABASE Format?
A.http://www.wotsit.org/search.asp?s=database
Q 5.22 How to check is current document in closing in MDI structure?
A.Hi, There is no direct mechanism to do this. Create your own class which is de
rived from CDocument and override this method.
virtual void OnCloseDocument( );
(OR)
I would suggest to make it by setting a flag, member of CDocument (eg. bool clos
ing), at the beginning of your OnCloseDocument override and unsetting it at the
end of the function
Q 5.23 what is EV_BREAK event detection pre-condition in serial comm program?
A. Hello, The EV_BREAK event is not reaised when the connection is lost. You sho
uld try the EV_ERR event. Look Here[^] for more info on serial events.
Breaks are some special action that some devices send across the network. It is
sometimes used to determine which device is allowed to send data.
Q 5.24 How to get the DPI value from C++ code?
A.It says right there in the documentation for GetDeviceCaps() that LOGPIXELSX a
nd LOGPIXELSY can be used to get the pixels per inch of a particular device. Als
o, the documentation for GetSystemMetrics() shows that SM_CXSCREEN and SM_CYSCRE
EN can be used to get the width and height, in pixels, of the screen.
Q 5.25 Is there a simple way of making the Exe for my program get a different ic
on depending on whether it's a debug or release build?
A. If you are using Visual Studio 6.0, it has an explicit tab for setting resour
ce compiler settings.
See Project Settings Dialog : Resources Tab : PREPROCESSOR DEFINITIONS Edit Fiel
d So, one of my projects,
for exmaple, already has _DEBUG defined for the debug build. Inside your RC or .
RC2 file, do something like this
#ifdef _DEBUG
1 ICON "MyDebug.Ico"
#else
1 ICON "MyRelease.Ico"
#endif

and see if that works for you. I would probably put it into the RC2 file, since
the resource editor usually yacks on 'unexpected' preprocessor statements.
Q 5.26 Is there anyway to handle the forced exit of an application by task manag
er?
A.As far as I know, you canno't stop the taskmanager from killing your app. The
reason for this is how the task manager terminates the application. The TM achie
ves this by cleaning up all resources of the process (just like a normal termina
tion, but without notification.)
Let me elaborate: Windows manages the CPU time that is given to a process / thre
ad with certain queues. If a process is able to run (Ready 2 Run, R2R), it waits
in a queue until it gets CPU time. If the process / thread is blocked, it waits
somewhere else until it becomes R2R. After getting that state, it is placed in
the queue. The taskmanager removes the process handle from this system, so the p
rocess will not get any CPU time anymore.
After doing that, windows will clean up all the resources user by that process (
as much as it can). So your process just disappears without any notification. Ho
pe this helps
(OR)
Here's some interestnig reading for you to understand what's going on:
http://blogs.msdn.com/oldnewthing/archive/2004/07/22/191123.aspx#191459
http://blogs.msdn.com/oldnewthing/archive/2004/07/23/192531.aspx
Q 5.27 how to determine the name of the Computer in VC++?
A. [GetComputerName] ,gethostname().
Q 5.28 how to change the position of a checkbox control during runtime?
A. What about [MoveWindow] and [SetWindowPos] Api!
Q 5.29 How can I show hidden folders when calling SHBrowseForFolder function?
A.http://groups-beta.google.com/group/microsoft.public.vc.mfc/browse_thread/thre
ad/6beca664725eb48a/af56d62d17b9d4e8
SHBrowseForFolder will not show hidden folders.
Q 5.30 How to convert UNICODE data into Ascii ?
A.Win32:
WideCharToMultiByte => Unicode to ANSI
MultiByteToWideChar => ANSI to Unicode
If you're using MFC 7.1:
CStringW strUnicode = L"Blah"; CStringA strANSI(strUnicode);
CStringW = Unicode string CStringA = ANSI string
(OR)
In Continuation with Mr Jack :-
1. wcstombs(convert wide character to Multibyte character),mbstowcs (just revers
e of previous)
2. String converion MACROS W2T,T2BSTR etc, have a look here for complete list ht
tp://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_atl_s
tring_conversion_macros.asp

Q 1.01 Is there any function to minimize the window?


A. ThatsAlok quoted :-
If you are using MFC: this->ShowWindow(SW_MINIMIZE);
If you are using Win32 API based application: ShowWindow(hWnd,SW_MINIMIZE);
Q 1.02 How do I stop appearing of the SQL Sever login dialog again and again?
A. renjith_sree quoted :-
Use CDatabase::noOdbcDialog as the second parameter in OpenEx() method. E.g.:
extern CDatabase oDb;
extern CString csConnection;
oDb.OpenEx(csConnection, CDatabase::noOdbcDialog );
This will suppress the login dialog.
Q 1.03 How can I access USB port (COM 5)?
A. Antti Keskinen quoted :-
The USB is a bus that resides in the computer. The low-level drivers (supplied b
y Microsoft) allow the bus to enumerate and identify a piece of hardware and the
n send a request to the registry to find the correct function driver for the dev
ice by using the vendor and product IDs returned by the USB descriptors. This is
how the bus works in a nutshell.
Your computer systems might have a pseudo-device driver that emulates a COM port
. When this driver is loaded, it opens a handle to the low-level bus drivers and
then creates a virtual COM port device. After this, passing a USB packet into t
he COM port is routed directly to the low-level drivers and thus into the bus. N
eedless to say, an erroneous packet might cause misbehavior on the system. This
is probably what your boss had in mind. You should ask him for clarification, th
ough.
When this pseudo-device driver is not in use, all devices attached to the bus ar
e represented by device objects. For each hardware device object that has a suit
able function driver available and loaded, a driver object also exists. Addition
ally, possible filter driver objects may exist. You can use the WinObj object vi
ewer (Google for it) to view all hardware device objects, driver objects and oth
er objects currently existing in your system. The same program can be used to ob
tain a valid name for a driver/device object. If you are operating on kernel mod
e, you can use this low-level name to open a handle into the driver/device. In u
ser mode, only the symbolic link names and a restricted list of device names are
available due to security restrictions imposed by Windows NT/2000/XP framework.
You can view all these through WinObj. The symbolic names can be found in the 'G
LOBAL??' subtree. Actual device names can be found from the 'Device' subtree. Fo
r reference, try looking for a normal COM port. You can find it lying around the
re somewhere. "\Device\Serial0" is COM1 for me.
From this list (Global??), you can even identify your USB device by looking at t
he vendor and product IDs. To get a rough idea whose device you're looking at, y
ou can use the Linux-USB group's list, which is "somewhat" regularly updated. It
can be found here[^].All USB devices are listed in the form "USB#Vid_xxxx&Pid_x
xxx&MI_xx#.....". The first is the vendor ID, the next the product ID. The last
one I'm not sure of.
Remember that a device might have multiple entries in WinObj's "GLOBAL??" subtre
e. The one we are interested in is \Device\USBPDO-X which refers to a physical d
evice object in the USB bus. Opening a handle to this device allows you to read/
write from as if reading/writing a file. Security restrictions might apply, thou
gh. You can view these through WinObj as well. If you can't view the properties
of an object, you don't have enough privileges. Looking at the Security tab, you
can see which users have rights to read/write/modify a device.
For an example, Logitech has a vendor ID of 046d hex. I have the Logitech MX500
optical mouse attached, and its product ID is c025 hex. Both of these are from L
inux-USB list. Thus, in "GLOBAL??", I have an entry "USB#Vid_046d&Pid_c025 etc"
which is a symbolink link to "\DEVICE\USBPDO-5". This is the physical device obj
ect for my MX500. Opening its properties, I can see that in user mode, I only ha
ve 'query state' privilege, allowing me to request status information about the
device. If I was logged in as an administrator, I could also 'delete' the object
, which means the device was logically detached from the bus. The bus would, how
ever, soon re-detect the device, re-load the drivers and re-create the device ob
jects.
I can't, in user mode, read or write from the device. For that purpose, I would
need to write a kernel-mode program. This program should create a virtual device
, say USB MX500 mouse, open the device handle for USBPDO-5, and route the comman
ds sent to the virtual device to the physical device and back. A crude hack, I'd
call it, but it would fill its purpose.
Q 1.04 What window message is processed when A window is maximized or minimized?
A. prcarp quoted :-
Look at WM_SIZE:
wParam = SIZE_MAXIMIZED, SIZE_MINIMIZED, SIZE_RESTORED, etc.
lParam = cx -> lo word cy -> hi word
Q 1.05 What is the most suitable solution for running a timer every 40 msec?
A. John M. Drescher quoted :-
The problem is that the time slice is much larger than 1 ms. See this article: T
ime is the Simplest Thing...
Antti Keskinen quoted :-
Windows is not the best platform for time-critical applications. If you must use
it, though, you could try increasing the priority of your application to maximu
m level. This ensures that the 40 ms (I assume milliseconds, here) timer is fire
d as close to 40 ms intervals as possible.
Increasing the priority of your application will cause other applications to los
e theirs: increasing the accuracy of your application might/will cause inaccurac
y/stiff response/high latency in other applications concurrently executing in th
e system. Pushing one application to real-time priority will most likely cause t
he operating system to appear 'locked up' while this single application is execu
ting. The timer will reach as close to 40 ms intervals as possible, though. That
's the price you'll have to pay.
When designing the real-time thread, you must make it as low-resource hog as pos
sible.
For an example, create a thread, increase its priority and call SetTimer Win32 A
PI routine with a pointer to the function that should run at 40 ms intervals. Th
en put this thread into a forever loop that can be interrupted, if necessary. Wh
en interrupted, the timer should be killed and the thread terminated. Note that
this will not cause the system to lock up, because the priority of the process i
tself has not been raised. You could use SetPriorityClass to pump up the process
priority as well. Before doing this, familiarize yourself with Scheduling Prior
ities[^] in the MSDN or in Visual Studio documentation. Misusing thread or proce
ss priorities is a sure way to get your computer locked up easily.
To set max priority for your MFC application's main thread, use AfxGetApp() to g
et the CWinApp object pointer, and call CWinThread::SetThreadPriority() with a p
arameter THREAD_PRIORITY_TIME_CRITICAL through this pointer. CWinApp derives fro
m CWinThread. MFC does not have a direct routine to pump up process priority. Yo
u'd need to use a mixed-mode call (CWinThread::operator HANDLE and SetPriorityCl
ass) to accomplish this.
A precisely 40 ms timer with not a single micro-second delay or advance is impos
sible in a modern operating system. For such a purpose, you'd need to design and
implement a micro-controller or similar solution.
Named events are used to schedule inter-process actions, or inter-thread actions
. For example, you could create an event object in a remote thread to mark when
this thread has ran a single loop. When the event object is signaled, a loop is
complete and the next loop is starting, if it's a continuous system. Event objec
ts can be global or local, determining how they are created. Global for inter-pr
ocess, local for inter-thread should be your general rule.
Even if you use named events, you would need some method to set the event to a s
ignaled state whenever 40 ms has passed. This will again lead you back to the ti
ming issue and the timers. Named events is the easiest way to signal other threa
ds or processes that your 40 ms interval has passed, though.
Q 1.06 What is the syntax of WM_GETTEXT for retrieving text from an edit box?
A. Ravi Bhavnani quoted :-
Many (actually most) Windows API calls that operate on windows work by sending t
he target window a message. WM_GETTEXT is the message sent to retrieve a window'
s text. Both these code fragments will get the edit control's text:
char szText [TEXTLEN]; HWND hWndEdit = window handle of edit control;
::GetWindowText (hWndEdit, szText, TEXTLEN - 1);
char szText [TEXTLEN]; HWND hWndEdit = window handle of edit control;
::SendMessage (hWndEdit, WM_GETTEXT,(WPARAM) TEXTLEN - 1,(LPARAM) szText);
Q 1.07 How to create a dialog which is not the main window, but its parent windo
w and owner window are all NULL, such as the conversation window in MSN Messenge
r?
A. Mr.Prakash quoted :-
Make the parent window of each dialog as desktop window by calling GetDeskTopWin
dow().
Q 1.08 How to capture WEBCAM using Visual C++ or API?
A. Cyberizen quoted :-
There is an SDK available from Microsoft Research called "Vision SDK". With this
SDK, you can connect to your webcam and capture images in a variety of formats.
I have worked on a project using this SDK in my third year project in BS. Tell
me if you want any additional help.
P.S.: Oh and I just learned that Microsoft has sold its Vision SDK product to so
me German company which might make it commercial so it might not be publicly ava
ilable. Fortunately, I found a website for you that allows you to download the M
icrosoft version.
Antti Keskinen quoted :-
The most effective way to use an installed webcam is to use DirectShow, which co
mes with DirectX 9.
The webcam driver, when it is installed and loaded, creates a DirectShow filter
for the video stream and pictures available from the camera. This filter offers
one or more interfaces, depending on what services the camera has. If you build
and operate a 'capture chain' (DirectShow term), you can capture live data from
the camera into a Windows window, a file or a network stream.
To use DirectShow in your programs, you must download and install the latest Dir
ectX SDK available freely from Microsoft. The DirectX documentation accompanying
this SDK has a few examples and code samples on how to create capture chains. T
he process of creating a chain is similar every time: the filters that join the
chain determine the nature, purpose and features of the chain.
For example, to use a webcam to get live data from the camera to a Windows windo
w, create a capture chain with the webcam filter and a Video Rendering Mixer fil
ter. VRM filter can render video data into a window you create and specify with
a HWND parameter. Remember that the VRM filter creates an auxiliary window which
is a child of the HWND you specify
. The auxiliary window has no title bar, system menu or anything else. It's just
a blank square which is constantly redrawn with video data. Thus you need an ac
tual top-level window which allows you to control the video display. You can't c
reate a program and just put a video window over the desktop, as you would then
have no way of closing the program without CTRL+ALT+DEL.
Q 1.09 What does the ^ do in C++?
A. toxcct quoted :-
^ is the bitwise exclusive-or operator
SO : 0x1100 ^ 0x1010----------- = 0x0110
that's why number ^= 1; means number = number ^ 1;
means number = 0 ^ 1; // == 1
PJ Arends quoted :-
See this: An introduction to bitwise operators.
Q 1.10 How do I do exponents in C++? If ^ is XOR...
A. Ryan Binns quoted :-
Use the pow() function.
Q 1.11 How do we run an EXE file at Windows startup?
A. goodmast3r quoted :-
Just make a shortcut in the Start>Programs>Startup
Arsalan Malik quoted :-
Add path (string value) of your EXE to following location in the registry: HKEY_
CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run.
vishalmore quoted :-
Add path of your EXE to following location in the registry: HKEY_LOCAL_MACHINE\S
oftware\Microsoft\Windows\CurrentVersion\Run.
Q 1.12 What's the difference between keyword and reserved word?
A. Sujan Christo quoted :-
Have a look @ the following links, it may help you: Wikipedia - Keyword, Reserve
d word.
Q 1.13 How can I prevent a dialog from resize and move?
A. Blake Miller quoted :-
The WM_GETMINMAXINFO message is sent to a window when the size or position of th
e window is about to change. An application can use this message to override the
window's default maximized size and position, or its default minimum or maximum
tracking size.
If you set both sizes the same, I am pretty sure your window's size will not adj
ust. You just make its minimum and maximum size the same. I have not tested this
exact behavior, however, it is just the first idea that came to my mind.
Q 1.14 How to write a .ini file of an application?
A. Greeeg quoted :-
The GetPrivateProfileXXX and WritePrivateProfileXXX functions do the job for you
.
Q 1.15 How to set the TAB order of a control at runtime manually?
A. Ryan Binns quoted :-
The tab order is simply the Z-order of the windows, so to change it use SetWindo
wPos()
Q 1.16 What's the functionality of DEBUG_NEW ?
A. PJ Arends quoted :-
It implements the ability of the debugger to be able to track the line number an
d file name of where any memory leaks were allocated.
DEBUG_NEW
Q 1.17 What are the differences between a DLL and a LIB file?
A. John R. Shaw quoted :-
In the past, if you linked in a normal .LIB file, then you had linked in every f
unction that was contained in that file, whether you used them are not. I do not
know if that is still the case, but it resulted in programs that where much lar
ger than required to do the job, since most of the functions linked in where not
used. Plus the fact that every program had there own versions of the same funct
ion code.
If the same functions from the same library are used in several programs, then y
ou should use a DLL. That way all the programs can share the same code: this red
uce the size of the individual programs and reduces the amount of disk space req
uired to store the programs and libraries they depend on. It also reduces the am
ount of memory required to load your program.
Q 1.18 Give me some method for determining the full path to my application?
A. Antony M Kancidrowski quoted :-
Here is a function that will do the job for you. Yea, I know it is global but yo
u can take the contents and wrap them in a class function if you like!
inline CString GetModuleLoadPath()
// Returns the load path of the module (ends in '\')
{
int Idx;
TCHAR ModName[_MAX_PATH];
if(!::GetModuleFileName(NULL,ModName,sizeof(ModName)) )
{
ASSERT(false);
return CString(_T(""));
}
CString LoadPath(ModName);
Idx = LoadPath.ReverseFind(_T('\\'));
if( Idx == -1 )
{
ASSERT(false);
return CString(_T(""));
}
LoadPath = LoadPath.Mid(0,Idx+1);
return LoadPath;
}
Q 1.19 What are Guard bytes ?
A. peterchen quoted :-
malloc_dbg calls malloc, but requests a few more bytes. These bytes are filled w
ith a predefined value. free_dbg then checks if these extra bytes still hold thi
s value. If they did, you probably wrote beyond the allocated memory (the VC Run
time prints a diagnostic message to the debug output). Typical implementations a
dd 4 bytes at the end.
In this case, using free instead of _free_dbg is often not a problem, but depend
ing on the implementation, it might leak the guard bytes. But if an implementati
on adds guard bytes *before* the memory provided to you (to detect underflows, w
hich are less common), using free instead of -free_dbg is likely to corrupt the
heap.
Q 1.20 How to debug a running DLL?
A. avenger_sb25 quoted :-
Well, if you are using the Visual Studio IDE, press F9 to set a breakpoint in th
e source file. Then, go to: Project>>Settings>>Debug tab. In the "Executable for
debug session:" edit box, browse and select the EXE file that is going to use y
our DLL. Then press 'OK'
Now run your program by clicking the '!' icon or on the toolbar. This will run t
he EXE that you selected earlier. Now if that program (EXE) makes use of an expo
rted function from your DLL, and if you have setup your breakpoints correctly, y
ou can debug your DLL......
renjith_sree quoted :-
Put the EXE file name in Project>Settings>Debug (executable for debug section).
[19 Dec to 27 Dec 2004]
Q 2.01 How to connect Modem to telephone ?
A. Antti Keskinen quoted :-
You should use TAPI (Telephony API) instead of Win32 CreateFile. See Visual Stud
io docs or MSDN for a reference and examples. TAPI is installed with Platform SD
K, so it comes bundled with most Visual Studio distributions, and/or you can dow
nload it from the Internet as well.
TAPI has a function pair called lineGenerateDigits and lineGatherDigits that gen
erate and gather pulse sequences that represent numbers. You can also send and m
onitor individual pulses with lineGenerateTone and lineMonitorTone.
These functions only exist in TAPI version 2.x. In version 3.x, the COM model is
introduced, and everything running on the phone line is considered a stream, wi
th terminal objects acting as sinks. For your case, I suggest TAPI 2.x, if possi
ble. The COM model is too complex for the functionality you require.
Q 2.02 How to identify a user who is having specific kinds of privileges? (i.e.
admin privilege, etc.)
A.DavidCrow quoted :-
Does NetUserGetInfo() do what you require?
Q 2.03 How to invoke a web service from a C++ project with a structure as parame
ter? top[^]
A.Antti Keskinen quoted :-
Are you using Visual Studio 6.0? If yes, consider moving to Visual Studio .NET 2
003. It has the excellent Add Web Reference wizard, which will generate wrapper
classes for Web Services. This means that if a Web Service's WSDL defines that i
t takes an array, the invoking method of the class also requires an array. If yo
u can't upgrade the environment, try fetching the latest SOAP Toolkit from Micro
soft and installing it. Its support will be retired in April 2005, but it's stil
l available for download.
The main reason for SOAP Toolkit deprecation is the coming of .NET Framework, wh
ich inherently supports Web Services. Using .NET requires Visual Studio .NET 200
2 or later, though, so you're in the same problem again. The SOAP Toolkit specif
ies the COM object SoapClient30. This COM object can initialize itself based on
a WSDL file. Having said that, obtain a WSDL file for the Web Service you wish t
o use, use COM to create the SoapClient30 object, initialize it with the WSDL fi
le, and you can directly call the method that takes an array as a parameter.
Q 2.04 How I can count the total number of characters typed in a RichEdit contro
l?
A. DavidCrow quoted :-
How about GetWindowTextLength()?
Q 2.05 How to prevent an MFC dialog based app being displayed on the taskbar?
A. Mohammad A Gdeisat quoted :-
I quote the following from MSDN 2003, I don't know if it really works but I hope
so: I will simply tell you the answer: you must create your dialog as a child o
f an invisible window that has WS_EX_TOOLWINDOW set, and you must make sure your
dialog has the WS_EX_APPWINDOW style turned off. If you read the documentation s
fine print, you might figure this out but only if you use a powerful magnifying gl
ass.
// pre-create window: set WS_EX_TOOLWINDOW style
//
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if (CFrameWnd::PreCreateWindow(cs))
{
cs.dwExStyle |= WS_EX_TOOLWINDOW;
return TRUE;
}
return FALSE;
}
// InitInstance: create dialog as child of invisible main frame
//
BOOL CMyApp::InitInstance()
{
CMainFrame* pFrame = new CMainFrame;
m_pMainWnd = pFrame;
pFrame->LoadFrame(IDR_MAINFRAME,WS_OVERLAPPED, NULL, NULL);
CMyDlg dlg(pFrame);
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
}
else if (nResponse == IDCANCEL)
{ }
return FALSE;
}
Q 2.06 How to set display resolution in Windows?
A. DavidCrow quoted :-
What about ChangeDisplaySettings()?
Q 2.07 How do I send a specific key to a window?
A. Antti Keskinen quoted :-
The WM_KEYDOWN message is sent to a window when the window has focus and a non-s
ystem keyboard key goes down and remains pressed. After the keyboard repeat dela
y, multiple WM_KEYDOWN messages are simultaneously generated. A non-system keybo
ard key is any key excluding F10 and keys pressed together with ALT. To simulate
an ALT + key combination, use WM_SYSKEYDOWN message.
In order to simulate a key press to a window, use WM_CHAR message. WM_CHAR messa
ges are not translated anymore, so the key code you issue for it will proceed di
rectly as-is to the receiving window. WM_KEYDOWN messages have virtual key-codes
that are translated to character codes. WM_CHAR messages have character-code (A
SCII) values with them.
To precisely simulate a key press (such as CTRL/SHIFT + key), you must generate
virtual key press events. This is much more complicated than just sending a sing
le message. Check SendInput in MSDN. In here, you will generate sequential keybo
ard events for each and every event of the key combination. Remember that pressi
ng CTRL + SHIFT + F, for example, consists of first setting CTRL, SHIFT and F ke
ys to pressed state, in order, and then releasing them, in inverse order. Note t
hat to target the key press combination, you must set the target window active b
y using SetFocus.
Also, if your program is running on a separate thread than the target program, y
ou must first attach the input streams by using AttachThreadInput, and detach th
em after you've synthesized the keystrokes.
Q 2.08 I need to check somehow when a process starts or exits. Any ideas how we
can do this?
A. ThatsAlok quoted :-
You have to set a system wide Hook on the process of type WH_CBT and listen for
WM_QUIT, WM_CREATE messages. SetWindowHookEx will be the API use in this case!
Q 2.09 How to convert between dialog units to pixels and vice versa?
A. DavidCrow quoted :-
This is a very bad idea. Dialog units are used for a reason, namely so that a pr
ogram does not have to be concerned with what resolution and font are currently
in use. By hard-coding controls based on pixel size, you have limited the portab
ility of your program to only one computer. See this comment for more.
Michael Dunn quoted :-
Use MapDialogRect() to do that conversion.
Q 2.10 How do I check what version of the compiler I am using?
A. Michael Dunn quoted :-
Test the _MSC_VER symbol. For VC 7, it's 1300; for VC 7.1, it's 1310; and for VC
6 with compiler version 12.00, _MSC_VER is 1200.
Q 2.11 How to output messages/text to screen at XP boot time from a Win32 consol
e application?
A. Michael Dunn quoted :-
Here's a start: HKLM\SYSTEM\CurrentControlSet\Control\Session Manager, string va
lue BootExecute holds the command line to run.
WoutL quoted :-
This page should be a big help for you...
e-sushi quoted :-
Guess I found some more useable stuff... Windows Driver Build Methods and Tools.
Q 2.12 How to use SetTimer( ) when in a MFC regular DLL?
A. Ravi Bhavnani quoted :-
SetTimer() is a method of the CWnd class. Your usage of the function invokes the
globally scoped ::SetTimer() Windows API call which takes a window handle as th
e first argument. Passing a value of "1000" will likely cause abnormal behavior.
You should pass your DLLClass object a valid CWnd (or window handle) which can b
e passed to the SetTimer() call within Test().
Q 2.13 Does anyone know how to upload files to a web server through HTTP by VC++
?
A. Neville Franks quoted :-
Have a look at: InternetWriteFile().
I assume you'll need permission / authentication to do this. It is probably bett
er to use FTP.
Q 2.14 How Can I draw inside an Edit control?
A. DELIVER THE PROMISE quoted :-
You can derive a class from CEdit and handle OnPaint(). You will have a DC there
. You can use it to draw like: dc.MoveTo() - dc.LineTo().
Or you can call: CDC* pDC = CEdit.GetDC(); pDC->MoveTo(), pDC->LineTo().
[28 Dec 2004 to 5 Jan 2005]
Q 3.01 How to get network IP address of computers?
A. DavidCrow quoted :-
To get the IP address of a machine, use gethostbyname().
Q 3.02 How to eliminate flickering when resizing a window?
A. SteveKing quoted :-
Try modifying CWnd::OnEraseBkgnd(..) which erases the background.
Q 3.03 How to find which window belongs to which EXE file?
A. Gary R. Wheeler quoted :-
Why not use the correct function: GetWindowModuleFileName().
Q 3.04 Is there any in-built function call to read the amount of memory or disk
free space?
A. Michael Dunn quoted :-
C++ has no such functions built-in because that kind of info is inherently platf
orm-specific. Check out the GlobalMemoryStatus() and GetDiskFreeSpaceEx() APIs.
Q 3.05 How to print/preview multiple pages?
A. PJ Arends quoted :-
Printing: Multipage Documents.
Q 3.06 Any suggestion about burning CD "on the fly" ?
A. Henry miller quoted :-
First, if you have a choice, use DVD+R or DVD+RW for this, because they have the
best support for preventing "under run". In fact if you are using CDs, to be le
gal you must be sure that your data stream is always big enough to write data wh
en the drive is ready (even if you are not!)! I break this rule all the time on
a modern drive, without too many problems, but if you sell this, you need to req
uire that your customers have a drive with good underun protection.
Next, go to www.t10.org and buy the MMC standards (you can download them too, bu
t not the latest versions...). You might want to consider joining, depending on
how technical your people are. t10 is the SCSI standards organization. Every CD
writer that is faster than 4x is SCSI! (It may be electrically IDE or USB, but i
t speaks the SCSI standard, so that is what you care about.) Read the standard s
everal times until you think you understand it.
Now, figure out how to send SCSI commands on your OS. On Windows NT/2000/XP, it
is a device_ioctl SCSI_PASSTHROUGH_DIRECT (or something like that). Windows 95/9
8/ME uses something else. UNIX is something different again, different for each
UNIX.
Next you need to figure out what standard you will write data in. I don't know a
nything about the video CD standard, so I can't help you there. You can define y
our own format if you don't care about nothing else being able to read the disk.
If you want to write a file, then you can either figure out UDF (I didn't, but t
his is perhaps the right way to go), or you can write ISO-9660. ISO-9660 is most
easily found under the name ECMA-119. Get the spec, and learn that inside and o
ut. There is just one detail you need to know: reserve a track at the beginning
of the disk, then write data to the next track, when done you write your directo
ry to the reserved track.
It took me about 4 months to write this myself (design through release). I had t
he advantage of a SCSI abstraction layer in place so I didn't need to worry abou
t many of the details you will need to learn. Once you understand the standards
and have a design, the code is only a couple weeks, but it takes a while to figu
re out how to read all the standards.
Q 3.07 Can somebody give me a list of the Virtual Key codes?
A. Heath Stewart quoted :-
Constants like these are defined in the headers that are installed with VC++. If
you find, for example, VK_UP then you can see all the others. They are defined
in winuser.h and documented at MSDN.
Q 3.08 When do we use extern "C"? Is this a compiler-specific feature?
A. Lim Bio Liong quoted :-
The extern "C" declaration is used to tell the C++ compiler not to mangle the sy
mbol which is being declared.
When the C++ compiler encounters a function name like "DisplayCurrentThreadId()"
which has not been declared as extern "C", it will emit a symbol for it which w
ill look like the following :
?DisplayCurrentThreadId@@YAXXZ
The actual symbol produced depends on the compiler used (the above was produced
by VC++ 6.0). This symbol will be used in the resulting OBJ file for linking pur
poses.
C++ has a variety of reasons for symbol name mangling, of course. But the reason
for the mangling of function names (both class functions and global ones) is to
enable function name overloading (i.e. using the same function name with differ
ent parameter types).
If extern "C" was used to declare the function, the symbol produced for it could
be:
_DisplayCurrentThreadId
This depends on the compiler used. But the bottom line is that no function name
overloading will be allowed (since the C language does not support this, hence e
xtern "C").
Q 3.09 How to write a web link to the Favorites folder ?
A. Michael Dunn quoted :-
See MSDN.
Q 3.10 Can anybody give me a code sample for getting the MS Outlook address book
?
A. Ravi Bhavnani quoted :-
Perhaps this[^] article will help?
Q 3.11 How to set window size of an MFC Dialog at runtime ?
A. Ravi Bhavnani quoted :-
See SetWindowPos() and MoveWindow().
Q 3.12 How do I make a combo box non-editable ?
A. cedric moonen quoted :-
Go into the properties of your combobox -> 'Style' tab and select 'DropList' in
the 'Type' combo.
Q 3.13 How do I create a DSN programmatically?
A. DavidCrow quoted :-
Use SQLConfigDataSource().
Q 3.14 How to show and hide the title bar of a modal dialog dynamically?
A. k_dehairy quoted :-
Try using this member function of the dialog:
//this will hide the title
ModifyStyle(WS_CAPTION,0);
//then call SetWindowPos()with cx and cy of your own
::SetWindowPos(m_hWnd,HWND_TOP,0,0,cx,cy,SWP_SHOWWINDOW);
To get the toolbar back:
//this will show the title
ModifyStyle(0,WS_CAPTION);
::SetWindowPos(m_hWnd,HWND_TOP,0,0,cx,cy,SWP_SHOWWINDOW);
Q 3.15 Could you provide me some resources (example: source code) to make global
hotkeys in MFC?
A. ThatsAlok quoted :-
Beginner's Tutorial - Using global hotkeys.
Q 3.16 How to add an icon to the system tray?
A. Michael P Butler quoted :-
Adding Icons to the System Tray
ThatsAlok quoted :-
One more in addition:
CTrayIcon - System Tray Icon Wrapper
Q 3.17 How to use a C based Library in a C++ environment?
A. Michael Dunn quoted :-
In your C++ code, do this:
extern "C"
{
#include "your_c_header.h"
}
Q 3.18 Which file is modified if I modify the project settings by pressing Alt+F
7?
A. ThatsAlok quoted :-
When you press Alt+F7, your Project.DSP will get modified.
Q 3.19 How to check if a file has been opened by any process or not?
A. Rajesh match quoted :-
Look for CFile::shareExclusive in MSDN.
cmk quoted :-
Spying a file system
Q 3.20 My Compiler points to WM_MOUSEWHEEL as "undeclared identifier", what is t
he problem?
A. PJ Arends quoted :-
From WinUser.h:
#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)
#define WM_MOUSEWHEEL 0x020A
#endif
Notice the #if? Make sure _WIN32_WINNT or _WIN32_WINDOWS is defined properly.
[6 Jan to 14 Jan 2005]
Q 4.01 How to set the font of CListCtrl header?
A. basementman quoted :-
//CFont Varible
CFont m_fArial;
//Create Arial Font
m_fArial.CreateFont(14,0,0,0,FW_BOLD,FALSE,FALSE,FALSE,
DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH,"Arial");
//Get Pointer of ListCtrl
CListCtrl *m_pList = (CListCtrl*)GetDlgItem(IDC_LIST1);
//Set Font if (m_pList)
m_pList->GetHeaderCtrl()->SetFont(&m_fArial);
The key here is to get a pointer to CListCtrl's embedded Header control.
Q 4.02 Will somebody refer me to source code for ZMODEM?
A. Ravi Bhavnani quoted :-
You could try porting this Unix example[^]. There's also some source here[^]. Al
so see this commercial source[^].
Q 4.03 How to use Crystal Reports in Visual C++?
A. Michael P Butler quoted :-
Have a look at this list of examples[^].
Q 4.04 Is there any s/w, utility to produce Audio Effect ?
A. Marcus Spitzmiller quoted :-
Last time I checked, DirectX does all of this in its DirectSound component: you
can research or download the SDK here.
Ravi Bhavnani quoted :-
I use Bass[^].
Q 4.05 How to detect what URL was clicked by the user ?
A. Michael Dunn quoted :-
The OnBeforeNavigate2 event passes you the URL about to be navigated to.
Antti Keskinen quoted :-
Instead of IWebBrowser2, use standard COM methods and register for notifications
from the DWebBrowserEvents interface. First query for IConnectionPointContainer
interface. Then ask for IConnectionPoint interface for DWebBrowserEvents. Then
register your class using IConnectionPoint::Advise.
The class you use must be derived from DWebBrowserEvents and must implement all
of its methods. Unused events should return S_OK. The event you're interested in
is DWebBrowserEvents::NavigateComplete. This event will have the final URL wher
e the client was directed to.
Q 4.06 Why threads are declared as static when used from a class?
A. Toby Opferman quoted :-
Functions used to be created as threads are defined as "static" when used with a
C++ class because there is an implied parameter that doesn't show up in code, t
he THIS pointer.
To avoid this confusion and make it simple, "static" class members only operate
on static data and not per-instance data and as such the "this" pointer is not p
assed in. So, it's easy to define the function as static and use it in CreateThr
ead without worries. Of course, they usually pass the object instance as the fir
st parameter anyway.
class x {
public:
static DWORD WINAPI MyThread(PVOID lParam)
{
x *pX = (x *)lParam;
// Happy Happy Joy Joy
}
}................
x pX = new x;
CreateThread(...., x::MyThread, pX);
As you see in the above example, the thread can be created and the system will p
ass in the "this" pointer and we will manually re-use it.
Another way to do this in C++ is to simply define a class function to be standar
d call, not fast call, and take "void" parameters.
class x
{
public:
DWORD WINAPI MyThread(void);
};
...
x *pX = new x;
CreateThread(..., x::MyThread, pX);
Why void parameters?
Because the system will now pass in the "this" pointer for you and in C++, the l
anguage hides this detail anyway.
Why stdcall and not fastcall?
STDCALL should pass the "this" pointer on the stack while fastcall passes the th
is pointer in the ECX register, which the system has no idea about.
Q 4.07 Where does Windows store log regarding dial-up connections?
A. Michael Dunn quoted :-
Look in your System event log, you'll see entries from the RemoteAccess service
when a connection is made or disconnected.
Q 4.08 How to change the language in UI (User Interface) dynamically?
A. Maximilien quoted :-
The best to do, is to use multiple resource files, one for each language you use
. Each resource will be in a DLL and will be loaded when the application starts
(or after a user selects a menu item).
Have a look at:
How to Create Localized Resource DLLs for MFC Applications.
Internationalization and Multiple Language Support.
Q 4.09 Any suggestion about Atomic clock and Time Zone Programming?
A. Mike Dimmick quoted :-
Modern versions of Windows (XP, 2003) come preconfigured to contact time.windows
.com using the Simple Network Time Protocol[^]. If you join a machine to a 2000
or 2003 Active Directory domain, the machine then gets its time from the domain
controller.
Second, I also need to display the time of other time zones, say I'm in LA, and
want to display the time for London and NY. Does any body have links to informat
ion on how one would go about determining the time in other time zones, area?
My World Clock[^] sample application does this. Source code is available at that
link - it's a C# application but uses OS function calls for the actual time con
versions. The tricky bit is handling daylight savings time - otherwise it would
be a simple offset calculation.
My biggest issue is with how the user can pick his location and how the software
knows the timezone/etc. at that location?
You'd have to have some kind of database of locations and the corresponding time
zones.
Q 4.10 How to read data from a sound card online?
A. K(arl) quoted :-
You could record this data using the Waveform-Audio interface. You may find info
rmation on how to use this API to record audio data at MSDN.
Q 4.11 What does IN/OUT mean when declaring variables?
A. DavidCrow quoted :-
Basically, it indicates when the variables will contain valid information. IN in
dicates that the variable has valid information when calling the function; OUT i
ndicates that the variable will have valid information after the called function
returns. See "pass by reference" and "pass by value" for related information.
Q 4.12 How can I get a specific folder's sector position?
A. Anonymous quoted :-
You may use ASPI or SPTI to read CD sector. Scan TOC to locate a specific folder
descriptor (see ISO 9660 ). To send an ASPI command, you may use "SendASPI32Com
mand" function from winaspi.dll, or use DeviceIOControl to send SPTI command.
[15 Jan to 23 Jan 2005]
Q 5.01 How to change the background color of an Edit Box?
A. Gary R. Wheeler quoted :-
You can change the background color of an edit control in a dialog by handling t
he WM_CTLCOLOR message in the dialog:
class MyDialog : public CDialog {
//...
COLORREF _BkgColor;
HBRUSH _BkgBrush;
};
BOOL MyDialog::OnInitDialog()
{
//...
_BkgColor = RGB(0,255,0);
_BkgBrush = ::CreateSolidBrush(_BkgColor);
}
HBRUSH MyDialog::OnCtlColor( CDC* pDC, CWnd* pWnd, UINT nCtlColor )
{
hbr = CDialog::OnCtlColor(pDC,pWnd,nCtlColor);
if (pWnd()->GetDlgCtrlId() == IDC_MY_EDIT_CONTROL) {
pDC->SetBkColor(_BkgColor);
hbr = _BkgBrush;
}
return hbr;
}
In the OnInitDialog() handler for the dialog, we initialize the background color
value and create a brush in that color. The WM_CTLCOLOR handler is called OnCtl
Color. The edit control for which we want to change the color has the resource I
D IDC_MY_EDIT_CONTROL. We set the text background to our background color using
SetBkColor(), and the overall background for the control by returning the brush
we created.
Q 5.02 How to increase the height of the header of a listcontrol?
A. Martin Koorts quoted :-
I've had a look at this, and can see no way - the CHeaderCtrl retrieved from the
CListCtrl has facility for only adjusting the width of a column. You'll have to
look at owner-draw.
Q 5.03 How to generate UNIQUE Key over the Network/Local Computer?
A. Martin Koorts quoted :-
The 'pattern' here is choosing whether to have;
a. unique IDs generated by a central authority (and relative to itself) - e.g. h
aving an autoincrement ID in a database table, or similar -
or...
b. generate unique IDs that are absolute (using UuidCreate/UuidCreatSequential)
- can be created anywhere and doesn't require contacting an authority.
Option a) in a distributed environment not only introduces a bottle-neck (consid
er many clients asking for IDs, or even ranges thereof, at the same time), but a
lso in terms of performance cannot compete with client local GUID generation (ne
twork time typically cannot compete with local CPU/HW time).
Unless the GUID generation causes a technical barrier, or you require IDs with p
redictable values, I suggest you use it.
Also, you might want to design it such that you can afford to start using GUIDs
now, and capitalise on this known, proven feature in your implementation; and at
a later stage, if you still find the performance or size of the IDs too large,
change it to something bespoke without compromising the design. In other words,
IDs are opaque and of variable size.
Q 5.04 How to get file-size of a file?
A. DavidCrow quoted :-
OK, what's wrong with:
DWORD SizeOfFile( LPCTSTR lpszFile )
{
DWORD dwSize = 0;
HANDLE hFile;
hFile = CreateFile(lpszFile, 0, 0, NULL, OPEN_EXISTING, ...);
if (hFile != INVALID_HANDLE_VALUE)
{
dwSize = GetFileSize(hFile, NULL);
// you may want to use GetFileSizeEx() instead
CloseHandle(hFile);
}
return (dwSize);
}
showe quoted :-
Try:
CFile myFile(lpszFileName, CFile::modeRead);
int len = myFile.GetLength();
Q 5.05 Does anybody know of an API for digital cameras?
A. Mike Dimmick quoted :-
Well, there's the Still Image API[^].
Q 5.06 How to hide & show menu bar dynamically?
A. Serge Krynine quoted :-
I think this code illustrates what you need:
void CShowHideMenuDlg::OnShowMenu()
{
// Load and add the new menu
CMenu mMainMenu;
mMainMenu.LoadMenu(IDR_MENU1);
ASSERT(mMainMenu);
SetMenu(&mMainMenu);
}
void CShowHideMenuDlg::OnHideMenu()
{
// Remove and destroy the old menu
SetMenu(NULL);
::DestroyMenu(GetMenu()->GetSafeHmenu());
}
Q 5.07 Please give me an example of RegEnumValue?
A. ThatsAlok quoted :-
First, take a look at RegEnumKey. RegEnumKey looks like this:
LONG RegEnumValue(
HKEY hKey, // handle to key to query
DWORD dwIndex, // index of value to query
LPTSTR lpValueName, // value buffer
LPDWORD lpcValueName, // size of value buffer
LPDWORD lpReserved, // reserved
LPDWORD lpType, // type buffer
LPBYTE lpData, // data buffer
LPDWORD lpcbData // size of data buffer
);
Now some code snippet:
char szNameOfKey[200];//Buffer
DWORD dwBufferSize=200;//Buffer Size
DWORD dwIndex=0;
CStringArray arrOfKeys;
Now, enumerate the HKEY_CURRENT_USER using RegEnumKey.
while(RegEnumKey(HKEY_CURRENT_USER, //
dwIndex++, //Index of Key to be Retrive
szNameOfKey,//Buffer of Key
dwBufferSize,//Buffer Size
NULL,//as documented in MSDN
NULL,//We don't need this right
NULL,//So no need of it
NULL)!= ERROR_NO_MORE_ITEMS)
{
//add New Found Key to array
arrOfKeys.Add(szNameOfKey);
//Restucture the size of Buffer as it modified during
//Enumeration
dwBufferSize=200;
}
//Now arrOfKeys Hold all the Enumerated Key
Q 5.08 How to disable/enable OK button in a property sheet?
A. R.selvam quoted :-
This link will help in this regard :- Hacking the CPropertySheet[^].
Q 5.09 How to get the serial number of a Compact Disc (CD)?
A. Dudi Avramov quoted :-
Check: Checking the serial Number of a CD.
Q 5.10 How to check if remote computer exists?
A. DavidCrow quoted :-
How about NetServerGetInfo(L"Computer42", 100, ...)? It will return ERROR_BAD_NE
TPATH if the machine does not exist.
Q 5.11 How to create nested directories?
A. Chris Losinger quoted :-
CreateDirectory(top);
CreateDirectory(top + "\\subdir1");
CreateDirectory(top + "\\subdir1\\+subdir2");
Q 5.12 How to get HWND of a dialog box?
A. Ravi Bhavnani quoted :-
You can access its window handle by calling GetSafeHwnd() or its member variable
m_hWnd.
Q 5.13 How can I know if the user is pressing on a button for more than 250 msec
?
A. Gary R. Wheeler quoted :-
Create your own button class CMyButton, which subclasses the existing CButton. A
dd a handler for the WM_LBUTTONDOWN message to CMyButton. In the handler, post a
notification to the parent dialog like this:
WPARAM wParam = MAKEWPARAM(GetDlgCtrlID(),BN_PRESSED);
LPARAM lParam = (LPARAM)m_hWnd;
GetParent()->PostMessage(WM_COMMAND,wParam,lParam);
where BN_PRESSED is a notification code you've defined. In your dialog, add a ha
ndler for the BN_PRESSED notification. In the handler, start a timer (try using
QueryPerformanceCounter). In your BN_CLICKED handler, get the value of the timer
and compare the difference.

Das könnte Ihnen auch gefallen