Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

45 Day Series: Codeproject VC++ Forum Q&A - IV

0.00/5 (No votes)
31 Jul 2005 1  
Collection of Q&A from VC++ forum between 25 April 2005 to 8 June 2005

Introduction

This article is compilation of Question and Answer, which were asked between 25 April 2005 to 8 June 2005 (45 Days) on Visual C++ .

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

[April 25 to May 3]

Q 1.01 How to get application currently activated, Name of Application and Window Caption ?
Q 1.02 How to get drive volume serial number in VC++ ?
Q 1.03 How to get the absolute path of the virtual folder like My Doucuments, Recycle Bin?
Q 1.04 Is there is any wrapper present for the Xml Parser in Visual C++?
Q 1.05 How i can change my console display mode to full screen mode in a dos based c++ program?
Q 1.06 How do i disable mouse wheel in comboBox (MFC) ?
Q 1.07 How i can run an Application file and then stop it ?
Q 1.08 Is there an "Official C++ rules" (perhaps guidelines is better than rules) web site?
Q 1.09 What is the best was to get the modified date/time of a file ?
Q 1.10 How to monitor Directory and Registry for any Modification or Updation?
Q 1.11 How to Detect Multiple VGA card in Display?
Q 1.12 How To Make Data Arrival to whole application ?
Q 1.13 Can i normalize this array into 0.0 to 0.1 without precision lost (and still maintain it as float)?
Q 1.14 How to run an application when Computer is about to shutdown?
Q 1.15 How to find Unicode FILENAMES from a certain Directory?
Q 1.16 How can I convert a int to a char*?
Q 1.17 How do I add File Version information in project?
Q 1.18 What the best way to sleep 1 ms?

[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 13 to May 21]

Q 3.01 How to determine if IE has finish loading?
Q 3.02 how to update edit control text ?
Q 3.03 How to get output of console program?
Q 3.04 How to add a progress bar in status bar using Win32 Api ?
Q 3.05 How to set background image for a dialog in MFC ?
Q 3.06 How to detect if an internet connection is available?
Q 3.07 How to Connect with website and Save Html Page in File ?
Q 3.08 How can you retrieve the HINSTANCE when you only have HWND ?
Q 3.09 How to Set root Folder in CFileDialog?
Q 3.10 How to get list of computers in specified workgroup?
Q 3.11 How to get the PhysicalDrive number which the logical drive located?
Q 3.12 How to programatically change the 'Work Offline' state to the normal 'Online' state?
Q 3.13 How to find the way to obtain the user names (or user id's) of the owners of process ?
Q 3.14 How to catch that user clicked 'x' button ?
Q 3.15 How To Launch email client with attachment ?
Q 3.16 How can I change the foreground color of an edit control?
Q 3.17 Is there a way of determining which OS running?
Q 3.18 How to get notified when user logoff?
Q 3.19 How can I find out how much memory (Private Bytes) my app currently has ?
Q 3.20 How can i want to detect whether certain path or directory exists or not?
Q 3.21 How to refresh Explorer window after Registry key changed?
Q 3.22 How can I determine the height in pixels of status bars?
Q 3.23 How do you duplicate a file?
Q 3.24 How to rotate a GDI object in VC++ without using setworldtransform?
Q 3.25 What is #pragma pack()?

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

[May 31 to June 8]

Q 5.01 How to remove close button from window?
Q 5.02 How to change foreground and back ground color of Edit Control?
Q 5.03 What is the structure of .RC file ?
Q 5.04 How to create a pop up message near the right hand corner of the task bar?
Q 5.05 how to make setup in visual c++ ?
Q 5.06 How to convert text file to BMP on runtime?
Q 5.07 How can I get the default printer which is connected on a pc directly or on a LAN?
Q 5.08 How to change the HTML currently loaded in IE, programmatically?
Q 5.09 How to use database created in MS Access 2000 in pc where MS Access in not Installed?
Q 5.10 What's the SDK function of the DeflateRect of MFC?
Q 5.11 If I add 100 to current date, how to get that modified date?
Q 5.12 How to send the Image File over the Socket ?
Q 5.13 How my service can impersonate Administrator (the service has access to the login information) while interacting with the Service Manager?
Q 5.14 Is there an SDK func that can convert big buffers from big endian to little endian ?
Q 5.15 How to convert the Hexadecimal into Binary?
Q 5.16 How programatically examine what text in clipboard?
Q 5.17 How to programmatically know that Webcam is attached to USB port?
Q 5.18 How to Send Email from my program without having email account?
Q 5.19 How to send Data/UDT thorugh Window Message?
Q 5.20 How to get the number of bytes/packets being received / sent over an NIC (standard ethernet card)?
Q 5.21 Could anybody refer me to RAW DATABASE Format?
Q 5.22 How to check is current document in closing in MDI structure?
Q 5.23 what is EV_BREAK event detection pre-condition in serial comm program?
Q 5.24 How to get the DPI value from C++ code?
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?
Q 5.26 Is there anyway to handle the forced exit of an application by task manager?
Q 5.27 how to determine the name of the Computer in VC++?
Q 5.28 how to change the position of a checkbox control during runtime?
Q 5.29 How can I show hidden folders when calling SHBrowseForFolder function?
Q 5.30 How to convert UNICODE data into Ascii ?

Q&Answer :-

[April 25 to May 3]

Q 1.01 How to get application currently activated, Name of Application and Window Caption ? [top^]

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!

Q 1.02 How to get drive volume serial number in VC++ ? [top^]

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

Q 1.03 How to get the absolute path of the virtual folder like My Doucuments, Recycle Bin etc.? [top^]

A. Dean Michaud Quoted :-

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

Q 1.04 Is there is any wrapper present for the Xml Parser in Visual C++? [top^]

A. cedric moonen Quoted :-

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

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.


Q 1.06 How do i disable mouse wheel in comboBox (MFC) ? [top^]

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


Q 1.07 How i can run an Application file for a While and then stop it ? [top^]

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


Q 1.08 Is there an "Official C++ rules" (perhaps guidelines is better than rules) web site? [top^]

A. stolid_rock Quoted :-

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

A. DavidCrow Quoted :-

How about [GetFileAttributesEx()]?

Ravi Bhavnani Quoted :-

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


Q 1.10 How to monitor Directory and Registry for any Modification or Updation? [top^]

A. ThatsAlok Quoted :-

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


Q 1.11 How to Detect Multiple VGA card in Display? [top^]

A. DavidCrow Quoted :-

Check out [EnumDisplayDevices()].


Q 1.12 How To Make Data Arrival to whole application / or make it global in whole application? [top^]

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.


Q 1.13 Can i normalize this array into 0.0 to 0.1 without precision lost (and still maintain it as float)? [top^]

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.


Q 1.14 How to run an application when Computer is about to shutdown? [top^]

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

Q 1.15 How to find Unicode FILENAMES from a certain Directory? [top^]

A. Ryan Binns Quoted :-

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

Q 1.16 How can I convert a int to a char*? [top^]

A. mkuhac Quoted :-

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

        

ThatsAlok Quoted :-

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

Q 1.17 How do I add File Version information in project? [top^]

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.

Q 1.18 What the best way to sleep 1 ms? [top^]

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]

Q 2.01 How to detect the IE/browser version? [top^]

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

Q 2.02 AfxGetAppName() is an MFC function, Is there is any Equivalent Win32 Api?[top^]

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.

Q 2.03 How to get Remote IP duirng Socket Connection? [top^]

A. ThatsAlok Quoted :-

use [getpeername] api


Q 2.04 How to Restrict my application to one instance only ? [top^]

A. Many Quoted :-

Q 2.05 How to use nmake? [top^]

A. PJ Arends Quoted :-

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

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

Q 2.07 How will i use unistd.h in VC++ or what the defination of this header file ? [top^]

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

Q 2.08 How to dynamically change the coloumn name of a list control? [top^]

A. rateep Quoted :-

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

Q 2.09 Does anyone know a Wrapper class to get samplerate bitrate and time of a mp3? [top^]

A. Alexander M. Quoted :-

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

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.

Q 2.11 Is it possible to get info between HWND and Process handle? [top^]

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

Answer :- cmk Quoted :-

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

A. Rama Krishna Vavilala Quoted :-

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

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.

Q 2.14 How to change attributes for a directory? [top^]

A. DavidCrow Quoted :-

This works for me:

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

A. DavidCrow Quoted :-

See if this helps.

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

A. DavidCrow Quoted :-

Try the Win32_Processor WMI class.

Q 2.17 Has anyone seen code that finds mersenne prime numbers? [top^]

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

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

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

Q 2.19 How to start at Program which start Hidden on Windows startup but Visible other wise? [top^]

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.

Q 2.20 What is this Error : "error C2664: 'TextOutW' : cannot convert parameter 4 from 'char [10]' to 'const unsigned short *'"? [top^]

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.

Q 2.21 How to Apply Xp Style to the Application ? [top^]

A. DavidCrow Quoted :-

[May 13 to May 21]

Q 3.01 How to determine if IE has finish loading? [top^]

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

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


Q 3.03 How to get output of console program? [top^]

A. Ravi Bhavnani Quoted :-

This [^] article may help.

DavidCrow Quoted :-

You can read here

Q 3.04 How to add a progress bar in status bar using Win32 Api ? [top^]

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.

Q 3.05 How to set background image for a dialog in MFC ? [top^]

A. DavidCrow Quoted :-

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

Q 3.06 How to detect if an internet connection is available? [top^]

A. ThatsAlok Quoted :-

this MS resource will help you http://www.pcausa.com/resources/InetActive.txt

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
for more info.

Q 3.07 How to Connect with website and Save Html Page in File ? [top^]

A. ThatsAlok Quoted :-

this article will help you in retrieving HTML pages form Internet server/Domain http://www.codeproject.com/internet/amhttputils.asp

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.

Q 3.08 How can you retrieve the HINSTANCE when you only have HWND ? [top^]

A. bharadwajgangadhar Quoted :-

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.

Q 3.09 How to Set root Folder in CFileDialog? [top^]

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

Q 3.10 How to get list of computers in specified workgroup? [top^]

A. DavidCrow Quoted :-

How about NetGroupGetUsers()?

Q 3.11 How to get the PhysicalDrive number which the logical drive located? [top^]

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.

Q 3.12 How to programatically change the 'Work Offline' state to the normal 'Online' state? [top^]

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

Q 3.13 How to find the way to obtain the user names (or user id's) of the owners of process ? [top^]

A. James R. Twine Quoted :-

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

CodeBeetle Quoted :-

Try This... http://codebeetle.com/page.php?al=process_username

Q 3.14 How to catch that user clicked 'x' button ? [top^]

A. Ravi Bhavnani Quoted :-

Handle WM_SYSCOMMAND and check for the case SC_CLOSE.

Q 3.15 How To Launch email client with attachment ? [top^]

A. James R. Twine Quoted :-

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

A. PJ Arends Quoted :-

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

Q 3.17 Is there a way of determining which OS running? [top^]

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.

Q 3.18 How to get notified when user logoff? [top^]

A. DavidCrow Quoted :-

Check out ISensLogon Interface.

Q 3.19 How can I find out how much memory (Private Bytes) my app currently has ? [top^]

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

A. Blake Miller Quoted :-

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 }

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

Q 3.21 How to refresh Explorer window after Registry key changed? [top^]

A. Michael Dunn Quoted :-

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

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.

Q 3.23 How do you duplicate a file? [top^]

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 -

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

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

Q 3.25 What is #pragma pack()? [top^]

A. Stlan Quoted :- Perhaps a simple example is better than any explanation.
First case:

#pragma pack(1)<br />struct MyStruct<br />{<br />BYTE a;<br />UINT b;<br />};<br />#pragma pack()


sizeof(struct MyStruct) will return 5 bytes (1+4=5)

Second case:

#pragma pack(4)<br />struct MyStruct<br />{<br />BYTE a;<br />UINT b;<br />};<br />#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.

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.
  • Priyank Bolia for Formatting this article :)

History

31 July 2005 :- Correction as quoted by Umut Alev :)and this is last update to this article!
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

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

A. Frank K Quoted :-

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

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

Q 4.03 How to access the variables declared in Doc.h from another .cpp? [top^]

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

Q 4.04 How to get all avaliable time zone? [top^]

A. ThatsAlok Quoted :-

These Api will help:-

EnumTimeFormats
EnumDateFormats
EnumCalendarInfo
EnumUILanguages
and for more Info visit this link:-
National Language Support[^]

Q 4.05 How i can set the text of the buttons in the toolBar ? [top^]

A. PJ Arends Quoted :-

Send a TB_SETBUTTONINFO message to the toolbar.

ThatsAlok Quoted :-

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

A. DavidCrow Quoted :-

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

A. DavidCrow Quoted :-

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

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

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

A. ThatsAlok Quoted :-

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

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.

Q 4.10 What is the difference between an accelerators and a hotkey? [top^]

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

Q 4.11 How to take the real part from a decimal number for example if i have 3.13 take only the 3 ? [top^]

A. Jack Squirrel Quoted :-

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

DavidCrow Quoted :-

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

cmk Quoted :-

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

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

Q 4.13 How to get the TYPE of control? [top^]

A. Jack Squirrel Quoted :-

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

A. ThatsAlok Quoted :-

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

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.

Q 4.16 How to establish the Window Dial up connection programmatically? [top^]

A. ThatsAlok Quoted :-

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

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.

Q 4.18 How to load the Dll function which argument can only known at runtime ? [top^]

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]

Q 5.01 How to remove close button from window? [top^]

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

Q 5.02 How to change foreground and back ground color of Edit Control? [top^]

A. ThatsAlok Quoted :-

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

Q 5.03 What is the structure of .RC file ? [top^]

A. Tom Archer Quoted :-

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

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

maybe this will help you:- http://www.codeproject.com/dialog/taskbarnotifier.asp

Q 5.05 how to make setup in visual c++ ? [top^]

A. ThatsAlok Quoted :-

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

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.

Q 5.07 How can I get the default printer which is connected on a pc directly or on a LAN? [top^]

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.

Q 5.08 How to change the HTML currently loaded in IE, programmatically? [top^]

A. ThatsAlok Quoted :-

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

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.

Q 5.10 What's the SDK function of the DeflateRect of MFC? [top^]

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


Q 5.11 If I add 100 to current date, how to get that modified date ? [top^]

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
    

Q 5.12 How to send the Image File over the Socket ? [top^]

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!

Q 5.13 How my service can impersonate Administrator (the service has access to the login information) while interacting with the Service Manager? [top^]

A. Blake Miller Quoted :-

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

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.

Q 5.15 How to convert the Hexadecimal into Binary? [top^]

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)

Q 5.16 How programatically examine what text in clipboard? [top^]

A. Ravi Bhavnani Quoted :-

See this CP article and this MSDN article.

Q 5.17 How to programmatically know that Webcam is attached to USB port? [top^]

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.

Q 5.18 How to Send Email from my program without having email account? [top^]

A. cadi Quoted :-

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

Q 5.19 How to send Data/UDT thorugh Window Message? [top^]

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.

Q 5.20 How to get the number of bytes/packets being received / sent over an NIC (standard ethernet card)? [top^]

A. ThatsAlok Quoted :-

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

S.Gopalakrishnan Quoted :-

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

Q 5.21 Could anybody refer 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^]

A. S.Gopalakrishnan Quoted :-

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

From what they say: 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 ? [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

History 

21 July 2005 :Correction as quoted by Umut Alev :)and this is last update to this article!
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here