# Codeproject VC++ Forum Q&A

## Introduction

Thanks to  people for their contributions on the Codeproject forum to help fellow peer in their need. I have change some people original comment to suit/maintain the look/feel of article (I beg apology for that). If i have miss something, please feel free to mail me or leave comment at bottom.

## Contents

### [May 4 to May 12]

Q 2.01 How to detect the IE/browser version?
Q 2.02 AfxGetAppName() is an MFC function, Is there is any Equivalent Win32 Api?
Q 2.03 How to get Remote IP duirng Socket Connection?
Q 2.04 How to Restrict my application to one instance only ?
Q 2.05 How to use nmake?
Q 2.06 What is the differences between command.com and cmd.exe?
Q 2.07 How will i use unistd.h in VC++ or what the defination of this header file ?
Q 2.08 How to dynamically change the coloumn name of a list control?
Q 2.09 Does anyone know a Wrapper class to get samplerate bitrate and time of a mp3?
Q 2.10 How can I get the ID of the dialog item which own the focus?
Q 2.11 Is it possible to get info between HWND and Process handle?
Q 2.12 How to Include " in a text string without ending the string?
Q 2.13 How to check the string if it is the number ?
Q 2.14 How to change attributes for a directory?
Q 2.15 How can i find out through code, the amout of processing power my application is using. ?
Q 2.16 How can i find out the information about my computers processor like - Manufacturer, Clock Speed etc?
Q 2.17 Has anyone seen code that finds mersenne prime numbers?
Q 2.18 how I can convert a DWORD (32 bits) value into a byte array of four bytes (32 bits)?
Q 2.19 How to start at Program which start Hidden on Windows startup but Visible other wise?
Q 2.20 What is this Error : "error C2664: 'TextOutW' : cannot convert parameter 4 from 'char [10]' to 'const unsigned short *'"?
Q 2.21 How to Apply Xp Style to the Application ?

### [May 22 to May 30]

Q 4.01 How to get these parameter like HDD id, Motherboard ID, CDROM-Drive id without using Registry and MFC ?
Q 4.02 How to get notified that the screensaver has become active?
Q 4.03 How to access the variables declared in Doc.h from another .cpp?
Q 4.04 How to get all avaliable time zone?
Q 4.05 How i can set the text of the buttons in the toolBar ?
Q 4.06  How to get the main icon of an EXE and then change the main icon of another EXE with that one?
Q 4.07 How to make sure someone is logged on to the computer ?
Q 4.08 How can i access the mapped network drive?
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?
Q 4.10 What is the difference between an accelerators and a hotkey?
Q 4.11 How to take the real part from a decimal number for example if i have 3.13 take only the 3 ?
Q 4.12 How to find  out if my mouse position is on a specific line ?
Q 4.13  How to get the TYPE of control?
Q 4.14 How to set timeout value in programm using csocket class ?
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?
Q 4.16 How to establish the Window Dial up connection  programmatically?
Q 4.17 How to crop an image in an application based on dialog?
Q 4.18 How to load the Dll function which argument only known at runtime ?

### [April 25 to May 3]

A. ThatsAlok Quoted :-

These Apis will Help :-
[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!

A.  DavidCrow Quoted :-

Either Use [GetVolumeInformation] or see here
http://msdn.microsoft.com/library/default.asp?url= /library/en-us/fileio/fs/enumerating_mount_points.asp

A. Dean Michaud Quoted :-

Check out the help on [SHGetSpecialFolderPath()] and [SHGetFolderPath()]

A. cedric moonen  Quoted :-

Maybe you'll find some interesting things http://www.codeproject.com/cpp/#Parsers

A. stolid_rock Quoted :-

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.

A. Rage Quoted :-

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...

A.  CodeBeetle Quoted :-

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

A. stolid_rock Quoted :-

A. DavidCrow Quoted :-

Ravi Bhavnani Quoted :-

or CFile::GetStatus() or _stat() or GetFileTime()

A. ThatsAlok Quoted :-

For Monitoring Directory/File changes  use [ReadDirectoryChangesW] and for registry monitoring[RegNotifyChangeKeyValue].

A. DavidCrow Quoted :-

Check out [EnumDisplayDevices()].

A. Gary R. Wheeler Quoted :-

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.

A. Christian Graus Quoted :-

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.

A. DavidCrow Quoted :-

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

A.  Ryan Binns Quoted :-

Look at [FindFirstFileW()] , [FindNextFileW()] and [FileFindCloseW]

A.   mkuhac Quoted :-

         TCHAR szBuffer[16];
INT iValue = 5;
::wsprintf(szBuffer, TEXT("%d"), iValue);



ThatsAlok Quoted :-

         int nNum=10;
char szNum[5];
itoa(nNum,szNum,10);



A. DavidCrow Quoted :-

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.

Blake Miller Quoted :-

Add a resource file (*.RC) to your project. Add a version information resource to the resource file.

A. Adi Narayana Vemuru Quoted :-

write your own delay routine using high-resolution APIs like [QueryPerformaceCounter()] and   [QueryPerformaceFrequency()] . you can achieve timer even in microseconds.

### [May 4 to May 12]

A. Priyank Bolia Quoted :-

look at the registry key  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Version  I hope this will work.

DavidCrow Quoted :-

just use [GetFileVersionInfo()] and [VerQueryValue()].

A. DavidCrow Quoted :-


char szPath[_MAX_PATH], szBase[_MAX_FNAME],
szExt[_MAX_EXT];

GetModuleFileName(NULL, szPath,sizeof(szPath));

_splitpath(szPath, NULL, NULL, szBase, szExt);



Michael Dunn Quoted :-

Call GetModuleFileName(), and then PathFindFileName() on the full path.

A.    ThatsAlok Quoted :-

use [getpeername] api

A.  Many Quoted :-

Q 2.05 How to use nmake?  [top^]

A. PJ Arends Quoted :-

A. DavidCrow Quoted :-

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").

A. ThatsAlok Quoted :-

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 <IO.H>
#include <PROCESS.H>

#endif /* _UNISTD_H */



Just Save it as Unistd.h and Include in your project

A. rateep Quoted :-

have you tried CListCtrl::SetColumn(.....)?

A. Alexander M.  Quoted :-

Here you can find all infos you need: http://www.codeproject.com/audio/MPEGAudioInfo.asp

A. ThatsAlok Quoted :-

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!

Jörgen Sigvardsson Quoted:-

What Alok said, with the addition that you can use int id = ::GetWindowLong(::GetFocus(), GWL_ID);

if you'd like to stay win32.

A. Full Question:

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)?

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.

A. Rama Krishna Vavilala Quoted :-

BSTR bstRet=SysAllocStringByteLen("Some text with the inch symbol\" and then end",44);

A. Christian Graus Quoted :-

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

Ted Ferenc  Quoted :-

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

PJ Arends Quoted :-

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.

A. DavidCrow Quoted :-

This works for me:

          if (! SetFileAttributes("c:\\ResOrg",FILE_ATTRIBUTE_READONLY))
{
DWORD dwError = GetLastError();
}



A. DavidCrow Quoted :-

See if this helps.

A. DavidCrow Quoted :-

Try the Win32_Processor WMI class.

A. DavidCrow Quoted :-

Google for the GIMPS project. I was going to refer you to the Mersenne site but it is currently down.

John M. Drescher Quoted :-

A.   PJ Arends Quoted :-

        for (int i = 3; i >= 0; --i)
{
length[3 - i] = (dwLength & (0xff <<(i * 8))) >> (i * 8);}



Michael Dunn Quoted :-

        DWORD dwLength=(DWORD) file.GetLength();
BYTE length[sizeof(DWORD)];
*(DWORD*) &length[0] = dwLength;



Bouli Quoted :-

Actually I've found the following way:

            length[0]=HIBYTE(HIWORD(dwLength));
length[1]=LOBYTE(HIWORD(dwLength));
length[2]=HIBYTE(LOWORD(dwLength));
length[3]=LOBYTE(LOWORD(dwLength));



A. ThatsAlok Quoted :-

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.

A. RChin Quoted :-

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.

A. DavidCrow Quoted :-

### [May 13 to May 21]

A.  Kharfax Quoted :-

You should create a browser helper object (Search BHO in Google) and handle the DOCUMENT_COMPLETE event.

A. Ravi Bhavnani Quoted :-

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.

Priyank Bolia Quoted :-

Use: DDX_Text(pDX, IDC_EDIT1, m_edit);
and after assigning the values use:
m_edit = "Test";
UpdateData( false );

A. Ravi Bhavnani Quoted :-

This [^] article may help.

DavidCrow Quoted :-

A. Jack Squirrel Quoted :-

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.

A.  DavidCrow Quoted :-

Does this help? http://www.codeproject.com/dialog/bmpdlg01.asp

A. ThatsAlok Quoted :-

Taka Muraoka Quoted :-

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

A. ThatsAlok Quoted :-

Ravi Bhavnani Quoted :-

As Alok has pointed out, you can use Ander's AmHttpUtilities class. If you need to do more involved parsing of the HTML content, see this[^] article.

To get hInstance. you can use AfxGetWinApp() sdk function. It retrives hInstance of the application.

PJ Arends Quoted :-

Use GetWindowLong() with the GWL_HINSTANCE flag.

A. PJ Arends Quoted :-

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();



A. DavidCrow Quoted :-

A. James R. Twine Quoted :-

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.

A. ThatsAlok Quoted :-

Check is this api [InternetGoOnline] help If DialUp you can use these api's too [InternetAutodial] and [Internetdial]

James R. Twine Quoted :-

I would look into InternetCheckConnection(...), it has a flag that forces connection; and InternetAttemptConnect(...).

A. James R. Twine Quoted :-

Have a look at the PSAPI and Tool Help Library in MSDN.

CodeBeetle Quoted :-

A. Ravi Bhavnani Quoted :-

Handle WM_SYSCOMMAND and check for the case SC_CLOSE.

A. James R. Twine Quoted :-

I do not think that you can, you may have to use MAPI (look up "Simple MAPI" in MSDN).

A. PJ Arends Quoted :-

handle WM_CTLCOLOR message and call SetTextColor() on the supplied DC.

A. Christian Graus Quoted :-

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 like Shog said, 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. I did that with TransparentBlt and AlphaBlend many years ago, so I could support W95 and still call them.

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.

A. DavidCrow Quoted :-

Check out ISensLogon Interface.

A. DavidCrow Quoted :-

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);

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);}



A. Blake Miller Quoted :-

Dude, you need to go here first:

if( (DWORD)-1 == GetFileAttributes(szFilePath) ){ tells you if it is missing }

Ravi Bhavnani Quoted :-

    //! 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);
}


ThatsAlok Quoted :-

Try [PathFileExists] api

A. Michael Dunn Quoted :-

Check out [SHChangeNotify()] - there might be a flag that will make Explorer refresh its views.

A. Blake Miller Quoted :-

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.

A.  Tom Wright Quoted :-

Try CopyFile or CopyFileEx here is the description:

 BOOL CopyFile
( LPCTSTR lpExistingFileName,
LPCTSTR lpNewFileName,
BOOL bFailIfExists
);



Tom Archer Quoted :-

In addition to what Tom said, I would also suggest looking 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 -

A. Christian Graus Quoted :-

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).

A. Stlan Quoted :- 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.

### [May 22 to May 30]

A. Frank K Quoted :-

A. DavidCrow Quoted :-

When a screen saver starts, it posts a WM_SYSCOMMAND message to the foreground window with wParam equal to SC_SCREENSAVE.

Flit Quoted :-

I saw this article in the MSDN, hope it helps. HOWTO: Know When Your Screen Saver Starts ID: Q238882

A. Jack Squirrel Quoted :-

An oldie, but a goodie: How To Get Current CDocument or CView from Anywhere        http://support.microsoft.com/default.aspx?scid=kb;en-us;108587

A. ThatsAlok Quoted :-

These Api will help:-

EnumTimeFormats
EnumDateFormats
EnumCalendarInfo
EnumUILanguages

National Language Support[^]

A. PJ Arends Quoted :-

Send a TB_SETBUTTONINFO message to the toolbar.

ThatsAlok Quoted :-

SetWindowText(HANDLE_OF_BUTTON, BUTTON_TEXT);

A. DavidCrow Quoted :-

Do you mean by actually modifying the .exe file? If so, check out BeginUpdateResource() and UpdateResource(..., RT_ICON, ...).

A. DavidCrow Quoted :-

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

A. DavidCrow Quoted :-

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().

A. ThatsAlok Quoted :-

M. Wohlers  Quoted :-

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.

A. Iain Clarke Quoted :-

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.

James R. Twine Quoted :-

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 <ALT>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 <ALT>key when a menu or menubar is active).

A. Jack Squirrel Quoted :-

   #include<math.h>
int nFloor = (int)floor(3.13);



DavidCrow Quoted :-

    Try:
double d = 3.13;
int n = d;



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.

A. Jack Squirrel Quoted :-

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

A. Jack Squirrel Quoted :-

Use GetDlgItem to get the window handle/object. Use GetClassName to retrieve the class name /type of.

A. ThatsAlok Quoted :-

[SetSocketOpt]

A. ThatsAlok Quoted :-

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);



Neville Frank Quoted :-

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

Toni78 Quoted :-

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.

A. ThatsAlok Quoted :-

A. Christian Graus Quoted :-

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.

A. munawar1968 Quoted :-

hi 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

### [May 31 to June 8]

A. Bob Stanneveld Quoted :-

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! .

Stlan Quoted :-

Try this: GetSystemMenu(FALSE)->EnableMenuItem(SC_CLOSE, FALSE);

A. ThatsAlok Quoted :-

Check these api's [SetTextColor],[SetBkColor]

A. Tom Archer Quoted :-

A. Michael Dunn Quoted :-

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. )

Giorgi Moniava Quoted :-

A. ThatsAlok Quoted :-

FreeWare Setup Maker!

or if you looking for sourcecode:-

A. PJ Arends Quoted :-

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.

A. PJ Arends Quoted :-

Have a look at CWinApp::GetPrinterDeviceDefaults()

Nilesh K. Quoted :-

Check out for EnumPrinters API, This should be able to get you available printers.

A. ThatsAlok Quoted :-

A. Michael P Butler Quoted :-

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.

A. Stlan Quoted :-

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.

ThatsAlok Quoted :-

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);
}



A. cedric moonen  Quoted :-

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



A. Trollslayer  Quoted :-

CSocketFile may do the job, like reading and writing files at either end.

ThatsAlok Quoted :-

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!

A. Blake Miller Quoted :-

Any information...
Call LogonUser to get token handle.
Call ImpersonateLoggedOnUser using the token handle.
Call RevertToSelf to go back to your original identity.

A. RichardS Quoted :-

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 < 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.

A. RichardS Quoted :-

ow do you want to store the binary? So you want a string that reads "0110 1111 1100 1001"? or is it in a 16-bit variable? As for swapping the bytes, store the bytes 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)

A.   Ravi Bhavnani Quoted :-

See this CP article and this MSDN article.

A.   FlyingTinman Quoted :-

If the webcam has a valid driver installed you just need to enumerate connected 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 "friendlyname"s in a menu from which the user can select one.

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 does not need authentication. You can use the SMTP-Server that is part of Microsoft's IIS.
2. Send directly to the recipient Just do a MX DNS lookup on the email adress and 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 directory) 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... An answer for the implementation details of MIME mails and the SMTP protocol would 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

A. Tom Archer Quoted :-

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;
}


Jack Squirrel Quoted :-

CString* pString = new CString(_T("Text"));
int nNumber = 100;
PostMessage(hMyWnd, MY_WM_MESSAGE1, reinterpret_cast<WPARAM>(pString),
reinterpret_cast<LPARAM>(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<CSTRING*>(wParam);
int nNumber = reinterpret_cast<INT>(lParam);
...delete pString;



Rouslan Grabar [Russ] Quoted :-

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.

A. ThatsAlok Quoted :-

Either look for IPHelper Apis or http://www.winpcap.org/

Hi,

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..

A.  DavidCrow Quoted :-

Have you seen this? http://www.wotsit.org/search.asp?s=database

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( );

liquid_ Quoted :-

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

A. Bob Stanneveld Quoted :-

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.

A.  DavidCrow Quoted :-

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.

A. Blake Miller Quoted :-

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.

A. Bob Stanneveld Quoted :-

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

Tom Archer Quoted :-

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

A. ThatsAlok Quoted :-

[GetComputerName]

DavidCrow Quoted :-

Another way is gethostname().

A. ThatsAlok Quoted :-

What about [MoveWindow] and [SetWindowPos] Api!

A. Mark Petrik Sosa Quoted :-

SHBrowseForFolder will not show hidden folders.

A. Jack Squirrel Quoted :-

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

ThatsAlok Quoted :-

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

## Points of Interest

Be in touch for more article in this series, as Visual Cpp Forum getting popular day by day. I have to read almost 6000 post to find Useful/Fine Q and A for this article and I believe it will continue in future too :). it really hectic job to read posts, now i can feel what going on the CP Editors :)

Idea and Design are taken from Mr. Michael Dunn (MS Visual C++ MVP) Cpp Forum FAQ Article.

## Special Thanks

• My Parents.
• All Active Contributor/Member to the Visual C++ forum/Codeproject, As without them this article wouldn't have seen day light.

## History

21 June 2005 :- Link Correction as Quoted by Mr. yuhaian plus Addtion of Stlan Pragma Pack tip
15 June 2005 :- First Article of 45 Day Series released
13 June 2005 :- Started Working on First Article

efer me to RAW DATABASE Format?  [top^]

A.  DavidCrow Quoted :-

Have you seen this? http://www.wotsit.org/search.asp?s=database

Q 5.22 How to check is current document in closing in MDI structure? [top^]

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( );

liquid_ Quoted :-

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? [top^]

A. Bob Stanneveld Quoted :-

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? [top^]

A.  DavidCrow Quoted :-

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? [top^]

A. Blake Miller Quoted :-

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? [top^]

A. Bob Stanneveld Quoted :-

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

Tom Archer Quoted :-

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++? [top^]

A. ThatsAlok Quoted :-

[GetComputerName]

DavidCrow Quoted :-

Another way is gethostname().

Q 5.28 how to change the position of a checkbox control during runtime? [top^]

A. ThatsAlok Quoted :-

What about [MoveWindow] and [SetWindowPos] Api!

Q 5.29 How can I show hidden folders when calling SHBrowseForFolder function? [top^]

A. Mark Petrik Sosa Quoted :-

SHBrowseForFolder will not show hidden folders.

Q 5.30 How to convert UNICODE data into Ascii ? [top^]

A. Jack Squirrel Quoted :-

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

ThatsAlok Quoted :-

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

## Points of Interest

Be in touch for more article in this series, as Visual Cpp Forum getting popular day by day. I have to read almost 6000 post to find Useful/Fine Q and A for this article and I believe it will continue in future too :). it really hectic job to read posts, now i can feel what going on the CP Editors :)

Idea and Design are taken from Mr. Michael Dunn (MS Visual C++ MVP) Cpp Forum FAQ Article.

## Special Thanks

• My Parents.
• All Active Contributor/Member to the Visual C++ forum/Codeproject, As without them this article wouldn't have seen day light.

## History

21 June 2005 :- Link Correction as Quoted by Mr. yuhaian plus Addtion of Stlan Pragma Pack tip
15 June 2005 :- First Article of 45 Day Series released
13 June 2005 :- Started Working on First Article

• 0
点赞
• 0
评论
• 0
收藏
• 扫一扫，分享海报

06-13 2861

09-13 2万+
03-11 977
06-25 1711
04-16 1万+
09-02 8103
11-27 1万+
04-10 1812
04-29 4427
06-10 7173
11-18 4156
01-05 507