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

kartaca-uyg-ser Kartaca应用程序服务开发任务 苏莱曼·卡尔坎(Suleyman Kalkan) 私钥代码: gAAAAABgUImSH93U9If0Ir4vcNIEGwiZijyj1PNu9Yy0XJKaqQy0BFiUX5KR_pbcAFWg9yn0z0VnOIqQiHsf3MJaJTUde8Z8HibbhynZPlwRm3r2DIVCRYCYwC2Z8pvjlUDZz2vYXcm74ZuKiUgel55z3h9VapVtmvXujpCgYv2VVQzHk7jQBn1HuIHJLrFRBaqf0iricLPm 设置 您可以使用以下命令运行该项目。 docker-compose up -d 实时仪表盘 localhost:3000 REST API 方法 网址 得到 本地主机:3000 / restApi /获取 邮政 本地主机:3000 / restApi /发布 偶像 本地主机:3000 立即下载

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

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

[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

[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

[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

 

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

xxxtube android神器 xxxtube android神器,首个用Mono For Android编写的商业App 立即下载

相关推荐

Tude-Python阶段3-4.zip

Tude-Python阶段3-4.zip

YouTube-8M: A Large-Scale Video Classification Benchmark

Abstract Many recent advancements in Computer Vision are attributed to large datasets. Open-source software packages for Machine Learning and inexpensive commodity hardware have reduced the barrier

人工智能 127万+

Avalonia使用CefNet 实现web-browsers(基于CentOS8 Arm64架构)

Avalonia使用CefNet 实现web-browsers(基于CentOS8 Arm64架构)

confused_kitten的博客 3803

2010-2012迷你博客

XiaJing: MySQLdb.escape_string(...) escape_string(s) -- quote any SQL-interpreted characters in string s. 回复 (13小时前) XiaJing: 公告:优快云个人空间即将改版.特别提醒:新版个人空间将不再提供迷你博客功能. 回复 (19小时前) f

XiaJing20060721的专栏 12万+

别再为GEE注册发愁了!用谷歌Cloud Project,5分钟搞定谷歌地球引擎账户(保姆级图文)

本文提供2024最新版谷歌地球引擎(GEE)账户注册的保姆级教程,通过谷歌Cloud Project快速完成注册,5分钟极速通关。详细解析注册前的准备、分步图解流程、常见误区及解决方案,帮助用户避开90%的注册陷阱,直达GEE核心功能区。

weixin_42557830的博客 199

为Codex添加任务完成提示音:提升开发效率的实用技巧

在自动化脚本开发和模型训练过程中,实时获取任务状态反馈是提升工作效率的关键。通过Hook机制,开发者可以在代码执行的关键节点注入自定义逻辑,实现各种自动化操作。Codex的Hook系统特别适合用于任务完成提醒,其post_execution节点能准确捕获执行结束事件。技术实现上,只需简单配置TOML文件并编写音频播放脚本,就能让系统在任务完成时自动播放提示音。这种声音反馈机制尤其适用于长时间运行的批量任务和模型训练场景,实测可提升30%以上的工作效率。结合动态音效选择和跨平台兼容方案,该技巧还能扩展为桌面通

weixin_26767391的博客 533

VIBTOOLBOX DOCUMENTATION

http://vibtoolbox.sourceforge.net/vtbman.html#asdvsd About vibtoolbox System of units Primer and example analysis vibtoolbox programs http://vibtoolbox.sourceforge.net/ About vibtoolbox Vibtoo...

liufengl138的专栏 5744

【AutoDL】使用云服务器跑深度学习代码

1.算力市场 租用服务器,选择自己心仪的服务器2.镜像可以选择一些基础的镜像,社区镜像里是git上有的环境。3.上传文件在文件存储中,选择上传的区,在右边点击上传,选择自己的文件上传到云服务器中。

weixin_45768644的博客 3701

javascript基础知识

}一旦执行到return代表函数结束,返回结果!如果没有执行return,函数执行完也会返回结果,结果就是undefined}}function(x){…}这是一个匿名函数,但是可以把结果赋值给abs,通过abs就可以调用函数!方式一和方式二等价假设在函数体中声明,则在函数体外不可以使用(非要想实现的话,后面可以研究一下闭包)}x = x + 2;在es6之前,怎么定义常量:只要用全部大写字母命名的变量就是常量,建议不要修改这样值。..............................

yunlin2000的专栏 1862

基于IMX429-IMX430-IMX432-IMX437系列传感器的SLVS-MIPI桥接方案设计与实现

本文详细介绍了针对索尼IMX429、IMX430、IMX432及IMX437系列传感器的SLVS-MIPI桥接方案设计与实现。针对工业视觉、车载摄像头等应用中主流SoC仅支持MIPI接口的痛点,提出基于FPGA(如Lattice Crosslink-NX)的透传桥接方案,将传感器输出的SLVS信号无损转换为MIPI CSI-2信号,确保数据完整性与低延迟,并探讨了硬件选型、逻辑设计及多传感器兼容性等关键问题。

weixin_29230901的博客 461

Win10 系统下VisualStudio2022 配置Open3D-0.18.0(C++)

Win10 系统下VisualStudio2022 配置Open3D-0.18.0

点云侠的博客 2655

Convex optimization 3.1 --- 凸优化问题 part1

1 introduction 在前面两个章节,回顾了凸集、凸函数、凸集和凸函数联系。从这章开始认识凸优化问题。 2 凸优化问题 2.1 优化问题的标准形式 2.1.1 优化问题的最优解 优化问题的最优解 解集可能存在两种极端情况 2.1.2 优化问题的解集 可行解 如果xix_ixi​满足fi(x)、hi(x)f_i(x)、h_i(x)fi​(x)、hi​(x),则称xix_ixi​是可行解。 最优解 如果xix_ixi​,使得f0(xi)=p∗f_0(x_i)=p*f0​(xi​)=p∗,则称x

降低学习速度,提高学习效率的地方 5529

CryoEM - 使用 ChimeraX 工具 操作 冷冻电镜的 MRC 密度图(Density Map) 教程

由冷冻电镜 CryoSparc 软件所生成的 Volume,需要观察其内部结构,建议使用 ChimeraX 进行操作。

AGI 4959

2021-01-18网络部(JavaScript数据类型)

一、字符串 1.字符串类型 (1)''abc'' 'abc' (2)转义字符 ①\ ' :单引号 ②\ n:换行 ③\ t :水平制表 ④\ u###:Unicode字符 (例:\ u42d表示中) ⑤\ x## (例:\ x41表示A) (3)多行字符串:` ` 例: var msg = `hello world 你好 世界` (4)模板字符串:${ } 例: let name="xiaoming"; let age=3; let msg=`...

m0_52386161的博客 633

STM32入门教程:人脸识别

STM32CubeMX配置 打开STM32CubeMX,创建一个新的工程,并选择你使用的STM32系列和具体型号。根据摄像头模块的规格,将摄像头的输出引脚连接到相应的STM32引脚上。人脸识别是一种非常常见的人工智能应用,它可以通过摄像头捕捉到的图像,识别出图像中的人脸并进行相关的分析和处理。在本教程中,我们将使用STM32开发板和相关传感器,通过指导你搭建一个基于STM32的简单人脸识别系统,并编写相应的代码来实现该功能。另外,为了达到更好的人脸识别效果,可能需要使用更高性能的处理器和更复杂的算法。

吃不胖. 374

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

20130901可注册域名列表

aeppv.com affjv.com afiun.com agthh.com ahmsp.com aixhr.com ajvcd.com aLoae.com ambLu.com anabL.com andwu.com anszL.com aoehq.com aoLdo.com apcnn.com aphcr.com apkoi.com aprty.com ar

落寞红尘 15万+

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

How To Nix Netscape 8

In order to flush Netscape 8 from your PC and restore XML rendering to Internet Explorer, Microsoft has recommended this work-around. Step 1: Uninstall Netscape 8.x"Unfortunately if Netscape 8 remains

于涛的专栏 32万+

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

E - 和風いろはちゃん / Iroha and Haiku(dp+状压)

Problem Statement Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order. Iroha is looking forX,Y,ZX,Y,Z-Haiku(defined below) in integ...

qq_40859951的博客 4101

Edge TPU Compiler实现INT8量化

本文深入解析Edge TPU与INT8量化的协同机制,涵盖编译流程、量化理论、模型设计原则及部署优化,通过实战案例展示在智能安防场景下的高效推理实现路径。

weixin_42596214的博客 912

前段JavaScript学习---狂神说java笔记

前段 JavaScript 狂神说java(JavaScript)原视频地址 解译 归属 备注 Script 脚本 脚本语言 alert 警觉,弹窗 Script console 控制台 Script log 日志,打印 console. Element 基本部分,测试 浏览器调试 Source 源码 浏览器调试 Network 网络 浏览器调试 Application 应用 浏览器调试 var 全局变量 Script let 局部变量

rzz65452064的博客 1457

Pytube keeps return 404 not found/Pytube 持续报错(404).

这个问题是由PyTube自身库中的一个小问题导致的(当然,你得确保已经开了梯子),目前已经修复了。 用 'pip install pytube --upgrade'更新一下你的库,再试试看。 This issue was inducedby a problem with the PyTube library. There is an issue about it here:https://github.com/pytube/pytube/issues/495 It is already fixed..

qq_34387395的博客 1万+

HTML5视频 youtube,html - Force HTML5 youtube video - Stack Overflow

Regarding the Youtube API Blog they are experimenting with their new HTML5 Video Player.Apparently to play a video in html5, you have to use the iframe embedding code :src="http://www.youtube.com/embe...

weixin_33575756的博客 1万+

youtube 可以下载一些英语

1. 将其url链接复制下来 2.访问一个可以下载youtube视频的网站:www.clipconverter.cc 3.然后在将第1步复制下来的url地址粘贴到“Media URL to Download”处,之后点”continue“会出现选择文件大小版本的选项,还有选择文件类型(如mp4,mov,….)之后再点击最下面的“star” 4.点击“Download” ...

keny-大成的博客 3430

apt-get、apt、yum、dpkg、rpm

apt-get 命令详解(中文)以及实例:http://blog.51yip.com/linux/1176.html linux yum命令详解:http://www.cnblogs.com/chuncn/archive/2010/10/17/1853915.html 配置 yum 源的两种方法:http://www.cnblogs.com/shuaix...

墨鱼菜鸡 2108

Ubuntu命令参考手册

Pages 10 HomeExcel的数据类型转换方法Git超级简明手册Ubuntu命令参考手册修改、重新生成和安装srpm源码包及deb包的方法在linux上用dd命令实现ghost功能最简单实现跨域的方法 使用nginx反向代理构建自己的debian软件包仓库用Redis轻松实现秒杀系统软件架构设计原则和模式(上):分层架构设计 Clone this wiki lo

Android系统攻城狮 5万+

利用 Claude Code Agent 框架一步一步实现 Deep Research:从 Skills 到 Subagent 的完整配置

用 Claude Code Agent 框架搭 Deep Research 工作流,从 command、skills 到 subagent 三层配置逐步拆解,含可复制片段与真实检索验证。先配好 TaoToken 的 Base URL、Key、Model ID 三件套,再跑通 /deep-research 命令,并附 401、local proxy failed 等常见报错排查。官网 https://taotoken.net/?utm_source=taotoken_aicg_blog_end

weixin_42608318的博客 27
上一篇: GetCurrentDirectory获得当前目录
下一篇: 45 Day Series: CodeProject VC++ Forum Q&A - I
goingup
博客等级 码龄22年 52粉丝 158原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值