Skip to main content

Visual C++ FAQs part-1

Q 1. How to get application currently activated, Name of Application and Window Caption ?
A. [GetForegroundWindow]for getting handle of application which currently have Keyboard 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/enumerating_mount_points.asp

Q 1.03 How to get the absolute path of the virtual folder like My Doucuments, Recycle 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/#Parsers

Q 1.05 How i can change my console display mode to full screen mode in a dos based 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], [GetConsoleScreenBufferInfo] 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_MOUSEWHEEL 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 [waitforsingleobject()] for waiting for object to execute and then call [terminateprocess()] to make 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) web 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 registry 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 whole application?
A. Make the data global. The simplest thing to do is to place it in stdafx.h, marking the declarations with the extern keyword. In the main program, where you retrieve the data from the registry, repeat the declarations without the extern keyword.

Q 1.13 Can i normalize this array into 0.0 to 0.1 without precision lost (and still maintain it as float)?
A. No - quite obviously if you compress the numbers into a smaller range, you will 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_QUERYENDSESSION message. When that message is received, return 0, start the "dialog based application." 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 Workspace 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 resource 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 [QueryPerformaceCounter()] and [QueryPerformaceFrequency()] . you can achieve timer even in microseconds.

Q 2.01 How to detect the IE/browser version?
A. look at the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\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 applications. 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 but would work with cmd.exe, although four folders would get created. To remedy this, 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 file ?
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/MPEGAudioInfo.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(::GetFocus(), 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 handle). 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 and 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 end",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 aware 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 account 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 application is using ?
A.http://www.codeproject.com/threads/getprocesstimes.asp?df=100&forumid=15846&select=799345#xx799345xx

Q 2.16 How can i find out the information about my computers processor like - Manufacturer, 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 but 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 Program 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 [use GetCommandLine() : to retrieve command line arguments]to hide or unhide your application.

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 your string with TEXT() or _T("") and it should work. This will use the appropriate 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_with_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 in (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/Domain 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 hInstance 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 structure, you have to set the lpstrInitialDir variable to point to a string containg 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 also 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 'Online' state?
A. Check is this api [InternetGoOnline] help If DialUp you can use these api's too [InternetAutodial] and [Internetdial]
(OR)
I would look into InternetCheckConnection(...), it has a flag that forces connection; 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" in 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/osversioninfo_str.asp

But if you use unsupported API's, then you need to dynamically load them, or your 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 has 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_NOSCALE, NULL,
&pdhfmtAvail);

pdhStatus = PdhGetFormattedCounterValue(hCacheBytes,PDH_FMT_LONG | PDH_FMT_NOSCALE, NULL, &pdhfmtCache);

pdhStatus = PdhGetFormattedCounterValue(hWorkingSet, PDH_FMT_LONG | PDH_FMT_NOSCALE, NULL,
&pdhfmtWorking);

wsprintf(szBuffer, TEXT("Physical Mem = %ldMB\n"),
(pdhfmtAvail.longValue + pdhfmtCache.longValue + pdhfmtWorking.longValue) / (1024 * 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 file to a specific folder hierarchy. (This function is in the dbghelp.dll, which you'll need to distribute depending on the target OS -
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/makesuredirectorypathexists.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 tells 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 without 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 another EXE with that one?
A. Do you mean by actually modifying the .exe file? If so, check out BeginUpdateResource() 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 WNetAddConnection2().

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=/library/en-us/vccore/html/vcconmfcvisualcversionnumbers.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvc60/html/redistribvc6.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 accelerator is a part of an accelerator table. (LoadAccelerator, TranslateAccelerator, etc.) It only works when your application has the keyboard focus.

A Hot Key is a a system wide key (RegisterHotKey, UnregisterHotKey). When pressed, 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 accelerators of other applications.
(OR)
Some also confuse one or both of those words with a "mnemonic", which is the underlined character you get on dialog controls allowing you to focus or activate that 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.13 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 returns the signed fractional portion of x. There is no error return.

x : Floating-point value. intptr : Pointer to stored integer portion. The modf function 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 returned. 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/msdn_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 end 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/~mgk25/iso-time.html
(OR)
difftime could be very useful when you want to jump from one time period to another. 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.phrack.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 remove 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=/library/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 TextOut to draw your text onto the bitmap the same as you would draw text onto the 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 printers.

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/bho.asp

Q 5.09 How to use database created in MS Access 2000 in pc where MS Access in not 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 definition of CRect::DeflateRect, you will see that it calls ::InflateRect by negating the parameters.
(OR)
No SDK available for that, you have to implement that. here is small logic to proceed :-
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 it over the connected socket to other END. this really work!,One of My project using similiar logic!

Q 5.13 How my service can impersonate Administrator (the service has access to the 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 little endian ?
A.I don't know of a SDK to do it, but switching endian's isn't a big deal. You can 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 direction). Now all you need is a loop:
void ConvertEndian (unsigned long int szLen, unsigned long int *pulBuf)
{
for (unsigned long int i = 0; i < w16bits =" (achOrig[0]" w16bits =" 6F" pszvalue =" _T(" ivalue =" 42;" psz =" (TCHAR*)wp;" i =" (int)" pstring =" new" nnumber =" 100;">(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 is 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 more 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 one 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 advantage 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 derived 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 closing), 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 should 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 and LOGPIXELSY can be used to get the pixels per inch of a particular device. Also, the documentation for GetSystemMetrics() shows that SM_CXSCREEN and SM_CYSCREEN 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 icon 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 resource compiler settings.
See Project Settings Dialog : Resources Tab : PREPROCESSOR DEFINITIONS Edit Field 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 manager?
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 achieves this by cleaning up all resources of the process (just like a normal termination, but without notification.)
Let me elaborate: Windows manages the CPU time that is given to a process / thread 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 process 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. Hope 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/thread/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 reverse of previous)
2. String converion MACROS W2T,T2BSTR etc, have a look here for complete list http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_atl_string_conversion_macros.asp

Comments

Popular posts from this blog

Simple Windows Registry Access

The Windows registry is an excellent place to store program information. From recent file lists to program settings, the registry provides programmers with a central location to store information for future use. Registry access can be quite simple, provided that you accept a few limitations. First, you must be willing to store your registry values on a per-user basis (rather than for all users). Second, you may only read and write values to your own application's registry branch. Poking around in arbitrary places in the Windows registry is somewhat more complicated than the method provided in this article. Do not assume that the constraints mentioned above render this method of registry access useless. I personally use this registry access method for all of my applications, using the advanced access method only when necessary. The simple method described below will do everything you need it to do for simple storage of application specific information. Enabling Registry Access The ...

Application Context Menus

Context menus (or "right-click popup" menus) come in two flavors: application-wide or control-specific. This article focuses on the former. Implementing the Application Popup Menu The first step in creating a context menu is simple: use the Visual Studio resource editor to create the menu you wish to display. Make sure that you give it a unique ID; I will use the value IDR_POPUP_MENU for this example. Add to the menu the various menu items that you want to include. Note that your context menu should only have one top-level item (under which all other menu items will be placed). The caption for this top-level item can be whatever you like since the user will never see it. If you are mapping menu items in this context menu to commands that already exist in the program (as is likely), make sure that you give each menu item the appropriate ID. For example, if the ID to my "Open File" command in my main application menu is ID_FILE_OPEN, I would give that same ID to the c...

Transferring Data From One Dialog Box to Another

In this exercise, we will learn how to exchange data from one dialog box to another. Start Microsoft Visual C++ On the main menu, click File -> New... Click the Projects property sheet and click MFC AppWizard (exe) In the Location box, specify a complete path for the folder, such as C:\Programs\MSVC In the Project Name: box, type ExoTransfer and click OK In the MFC AppWizard - Step 1, click the Dialog Based radio button. Click Finish and click OK Design the default dialog box by adding an Edit Box IDentified as IDC_FIRSTNAMEDLG1 Add a second Edit Box IDentified as IDC_LASTNAMEDLG1 Add one more Edit Box IDentified as IDC_FULLNAMEDLG1 Add a Button IDentified as IDC_CREATEACCOUNT and the Caption as C&reate Account... Set all three Edit controls read only by clicking the Read-Only check box of each (in the Edit Properties window). Press Ctrl + W to access the ClassWizard (I using Microsoft Visual C ++ 5/6 for this exercise and not MSVC .NET) Click Member Variables and Add Variabl...