Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VC9.0

45 Day Series: CodeProject VC++ Forum Q&A - V

4.83/5 (14 votes)
25 Jul 2010CPOL21 min read 52K  
Collection of Q&A from VC++ forum

Introduction

Nothing unusual... this article is a compilation of questions and answers which were asked on the Code Project Visual C++ forum. Also, this is the third article of the 45 Days series. I hope, I will bring more on this series.

Thanks to people for their contributions on the CodeProject forum to help fellow peers in their need. I have changed some original comments to suit/maintain the look/feel of article (I beg apology for that). If I have missed something, please feel free to mail me or leave a comment at bottom.

Content

MFC

MFC01How to convert Integer,Float to CString?
MFC02How to compare bitmap image in MFC?
MFC03How can I track application memory usage from application itself?
MFC04What is the difference among the OnClose(),OnDestroy() and the DestroyWindow()?
MFC05How to set font size of static text?
MFC06How to create a web server in VC++(MFC)?
MFC07How can find weekday name from date in dd/mm/yyyy format?
MFC08why CWinApp Class having one object only?
MFC09How to print Transparent Value over the screen?
MFC10How to to calculate the future date from number of seconds available from now?
  

WINDOW32

 
Win3201How to get path(C:\Users\Public) programatically in Window Vista?
Win3202How name decoration work  in DLL?
Win3203Can I fill my moving dialog, Bubble Dialog with gradient color?
Win3204How to change current working directory in C/C++?
Win3205How to get my hard disk name and all the information related to it?
Win3206How to get LoginNames of all Users in my Domain?
Win3207How can I get Temp Folder path?
Win3208What is the easiest way to convert a CString into a standard C++ string?
Win3209How can I get the name of Win CE device?
Win3210How can I catch a Windows PowerDown (or Hibernation) Event and Way to Disable it?
Win3211How can I check the existence of a Registry Key using C++?
Win3212How to create Shared Files and Folders ?
Win3213The coordinates are the client area, but arent correct if the window is being scrolled. What can i do?
Win3214How to run dll using Rundll32.exe ?
Win3215How to detect user's language for user interface?
Win3216How to check process memory usage?
  

GENERAL

 
GEN01How to call  a function in an external .js file from C++ ?
GEN02How can I get Total number of days of a Year.(wheter 365 or 366)?
GEN03How to develop windows system startup application?
GEN04How to deploy executable build in VS2005?
GEN05How to get XP Style Look?
GEN06How to convert the HEX format to human readable value?
GEN07How can a program detect that the local computer is connected to a network ?
GEN08I want built app to communication through USB port. How to start ?
GEN09How to set an expiration date on an application or dll?
GEN10Accessing with NULL pointer without crash?
GEN11How do I declare initialise a global variable, exported from one dll and use it from various files?
GEN12How to convert char arrays containing embedded NULL characters to BSTR?
GEN13How to call .NET Managed DLL from Unmanaged codes?
GEN14How to get project name at compile time?
GEN15How to detect if pointer points to the stack or the heap?
GEN16Is it possible to create an NFS mount in C++?
GEN17What is the significance of #pragma once ?
GEN18How CWebBrowser2 can use Proxy ?
GEN19Vista elevation problem ?
GEN20How to read from bluetooth?
  

FUNNY

 
FUN01How to scan or identify a physical damage (like scratch or spot) in a blank writable CD?
FUN02How to display a messagebox after the application is closed ?
FUN03On lighter side About Polymorphism!
  

Answer

 
  

MFC

 
  
Question(MFC01)How to convert Integer,Float to CString? [Top]
AnswerIn ANSI:-
CStringA strFormat;
// For Integer

strFormat.Format("%d",10);
// For Float

strFormat.Format("%f",10.05);
In Unicode:-
CStringW strFormat;
// For Integer
strFormat.Format(L"%d",10);
// For Float

strFormat.Format(L"%f",10.05);
 
Question(MFC02)How to compare bitmap image in MFC?[Top]
Complete QuestionSuppose i have 2 bmp files:- 1 containing alphabet AB & 2 containing alphabet AC.
Now i want to check how to compare both the images by comparing first (A-A & A-C) and (A-A & A-B).
As soon as A-C or A-B is found it should give a error message that images are not same.
So how Can i perform this unique work in MFC.
AnswerAnswer#1
If you want to learn about image processing try doing a google search. There is already plentiful resources on the internet for the subject."http://en.wikipedia.org/wiki/Digital_image_processing" rel="nofollow"> Digital Image Processing[^]
  • There are even books[^]. IImagine that!

    Answer#2
  •  
    Question(MFC03)How can I track application memory usage from application itself?[Top]
    AnswerSuggestion#1 : Use GlobalMemoryStatus()

    Suggestion#2: Try the CMemoryState class. It will work only in debug build. You can also use the GetProcessMemoryInfo() API before and after the function.
     
    Question(MFC04)What is the difference among the OnClose(),OnDestroy() and the DestroyWindow()? [Top]
    AnswerWM_CLOSE is sent when you click the close button (or hit Alt+F4 or close the window some other way). Normally, you would do some cleanup and then call DestroyWindow(). If you let DefWindowProc handle WM_CLOSE, it will call DestroyWindow() for you. WM_DESTROY notifies you that the window is being destroyed.
     
    Question(MFC05) How to set font size of static text?[Top]
    Answeryou can use.
     CFont *m_Font1 = new CFont();
    CStatic *staticCtl =(CStatic *) GetDlgItem(IDC_STATIC1);
    m_Font1->CreatePointFont(100,_T("Arial")); 
    staticCtl->SetFont(m_Font1);
     
    Question(MFC06)How to create a web server in VC++(MFC)?[Top]
    AnswerSuggestion#1
    Start with a HTTP 1.0, the protocol is quite simple to implement (compared to HTTP 1.1).
    http://ftp.ics.uci.edu/pub/ietf/http/rfc1945.html

    Suggestion#2
    Here is a very old (circa 1996) article that describes how to write an HTTP/1.0 server using MFC: "Write a Simple HTTP-based Server Using MFC and Windows Sockets" by Dave Cook, February 1996 issue of Microsoft Systems Journal, at http://www.microsoft.com/msj/archive/S25F.aspx
     
    Question(MFC07)How can find weekday name from date in dd/mm/yyyy format?[Top]
    AnswerFollowing code will help
    COleDateTime dt("9/24/2008");
    CString dayNameLong = dt.Format("%A");
    CString dayNameShort = dt.Format("%a"); 
     
    Question(MFC08)why CWinApp Class having one object only?[Top]
    AnswerAnswer1:

    Because MFC was designed that way. The one object wraps all the app instance info that Windows apps have only one of, like the HINSTANCE, and the commandline params passed. It also holds any other application-wide stuff of which there can only be one. That makes it a nice place to hide app-wide variables that in the old days would be global.

    Answer2:

    because it the base class for the application class. It is needless to have more than one application class for one application. The implementation has dependency on the global object obtained from AfxGetApp(), which is used by the AfxWinMain from winMain. Then it is similar to ask why only one main function for an application.

    "The main application class in MFC encapsulates the initialization, running, and termination of an application for the Windows operating system. An application built on the framework must have one and only one object of a class derived from CWinApp." from msdn.

     
    Question(MFC09)How to print Transparent Value over the screen?[Top]
    Complete Questionhow do I display a value on top of the screen. I have a picture box.. and there is a picture on the picture window. now on the picture i need to show a value but this control has to be transparent. how can i achieve that?
    Answerplease try it as follows.
    (m_pic.GetDC())->SetBkMode(TRANSPARANT);
    (m_pic.GetDC())->TextOut(0,0,"hello");
    hope this should work.
     
    Question(MFC10)How to to calculate the future date from number of seconds available from now?[Top]
    AnswerFollowing code will help achieve future date from current date
     CTimeSpan sPan(0,0,0, 86400 );// 1 day
    CTime CurTime = CTime::GetCurrentTime();
    CurTime +=sPan;
    CString csTime = CurTime.Format(_T("%A, %B %d, %Y"));
    
    AfxMessageBox(csTime );
    
      

    WINDOW32

     
      
    Question(WIN3201)How to get path(C:\Users\Public) programatically in Window Vista?[Top]
    Complete QuestionI need to create a directory under c:\Users\Public. My os is Vista. I am using VC++. I cannot use latest SDK. Can I know to to get to that path programmatically using VC++6.0
    AnswerThe standard way is to use the SHGetKnownFolderIDList()[^]function by passing the REFKNOWNFOLDERID as FOLDERID_Public. This function is available only in vista and in you case since you cannot install latest SDK, you have to dynamically load the function from the shell32.dll.

    How ever I think the following code will also work( I didnt test it because i dont have vista right now )

    C++
    TCHAR tcPath[MAX_PATH];
    GetEnvironmentVariable( _T("PUBLIC"), tcPath, MAX_PATH );
    
     
    Question(WIN3202)How name decoration work  in DLL? [Top]
    Complete QuestionI think extern C is enough to prevent name from decorated, but when we export function names from a DLL using dllexport, even if we declare at the same time with extern C, but without a DEF file to define un-decorated exported function names, the name is still decorated.
    I do not know why DEF file is needed? extern C is not enough to control name decoration for both DLL exported names and current DLL model linking?
    AnswerDon't think this is exactly true. C functions are also decorated based on calling convention.

    See: http://msdn.microsoft.com/en-us/library/x7kb4e2f.aspx[^]


    As an example; in .cpp:
    extern "C" {
    __declspec(dllexport) int MyFunc ( int A ) { return(A*2); }
    }
    
    and in .def (in EXPORTS):
    MyFunc @3
    
    'DumpBin /exports mydll.lib' will report '_MyFunc' as the name.
    
    If, we used:
    extern "C" {
    __declspec(dllexport) int __stdcall MyFunc ( int A ) { return(A*2); }
    }
    

    then, even with the .def entry, dumpbin will report '_MyFunc@4' as the name

    The default _cdecl is standard, the _ prefix is used by all vendors.
    Other calling conventions are vendor specific (__stdcall is only MS i think).

    Use extern "C" {} _and_ the default _cdecl when you want to create a dll with one compiler that can be called by an exe compiled using any other compiler.

    If you have a .cpp file all functions will be named using C++ naming - mangled. If you have a .c file all functions will be named using C naming - mangled as described in the url i posted in previous message. The default _cdecl .c naming is considered by most to be unmangled, even though it is (leading _).

    Using extern "C" in a .cpp file, or extern "C++" in a .c file, just allows you override the default naming the compiler uses based on the file extension (.c or .cpp).

    In your dumpbin output MyFunc1 _is_ mangled (_MyFunc). The default is so standard that the _ is often dropped from display - but it is there.
     
    Question(WIN3203)Can i fill my moving dialog, Bubble Dialog with gradient color?[Top]
    AnswerSay if I have a 10x10 rect located at 50,50 on the screen, the function wants

    RECT gradRect = {0,0, 10,10} not RECT gradRect = {50, 50, 60, 60} like you would expect.

    Sorry for the confusion there.

    As for the bool isVerticle param, you can run the gradient from leftToRight or topToBottom.
    isVerticle = true ---> topToBottom gradient
    isVerticle = false ---> leftToRight gradient


    Here's a 45 second example. You need to link in gdi32, user32 and kernel32.
    No points for guessing which IDE I've used Shucks
    #include <windows.h>
    
    /*  Declare Windows procedure  */
    LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
    
    /*  Make the class name into a global variable  */
    char szClassName[ ] = "CodeBlocksWindowsApp";
    
    int WINAPI WinMain (HINSTANCE hThisInstance,
                         HINSTANCE hPrevInstance,
                         LPSTR lpszArgument,
                         int nCmdShow)
    {
        HWND hwnd;               /* This is the handle for our window */
        MSG messages;            /* Here messages to the application are saved */
        WNDCLASSEX wincl;        /* Data structure for the windowclass */
    
        /* The Window structure */
        wincl.hInstance = hThisInstance;
        wincl.lpszClassName = szClassName;
        wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
        wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
        wincl.cbSize = sizeof (WNDCLASSEX);
    
        /* Use default icon and mouse-pointer */
        wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
        wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
        wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
        wincl.lpszMenuName = NULL;                 /* No menu */
        wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
        wincl.cbWndExtra = 0;                      /* structure or the window instance */
        /* Use Windows's default colour as the background of the window */
        wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;
    
        /* Register the window class, and if it fails quit the program */
        if (!RegisterClassEx (&wincl))
            return 0;
    
        /* The class is registered, let's create the program*/
        hwnd = CreateWindowEx (
               0,                   /* Extended possibilites for variation */
               szClassName,         /* Classname */
               "Code::Blocks Template Windows App",       /* Title Text */
               WS_OVERLAPPEDWINDOW, /* default window */
               CW_USEDEFAULT,       /* Windows decides the position */
               CW_USEDEFAULT,       /* where the window ends up on the screen */
               544,                 /* The programs width */
               375,                 /* and height in pixels */
               HWND_DESKTOP,        /* The window is a child-window to desktop */
               NULL,                /* No menu */
               hThisInstance,       /* Program Instance handler */
               NULL                 /* No Window Creation data */
               );
    
        /* Make the window visible on the screen */
        ShowWindow (hwnd, nCmdShow);
    
        /* Run the message loop. It will run until GetMessage() returns 0 */
        while (GetMessage (&messages, NULL, 0, 0))
        {
            /* Translate virtual-key messages into character messages */
            TranslateMessage(&messages);
            /* Send message to WindowProcedure */
            DispatchMessage(&messages);
        }
    
        /* The program return-value is 0 - The value that PostQuitMessage() gave */
        return messages.wParam;
    }
    
    
    
    // frees you from using the GDI function, which requires a region
    void GradientFillRect(HDC hdc, LPRECT rcGradient, COLORREF start, COLORREF end, BOOL isVertical)
    {
    	BYTE startRed = GetRValue(start);
    	BYTE startGreen = GetGValue(start);
    	BYTE startBlue = GetBValue(start);
    
    	BYTE endRed = GetRValue(end);
    	BYTE endGreen = GetGValue(end);
    	BYTE endBlue = GetBValue(end);
    
    	HBRUSH endColor = CreateSolidBrush(end);
    	FillRect(hdc, rcGradient, endColor);
    	DeleteObject(endColor);
    
    	//Gradient line width/height
    	int dy = 1;
    
    	int length = (isVertical ? rcGradient->bottom - rcGradient->top : rcGradient->right - rcGradient->left) - dy;
    
    	for (int dn = 0; dn >= length; dn += dy)
    	{
    		BYTE currentRed = (BYTE)MulDiv(endRed-startRed, dn, length) + startRed;
    		BYTE currentGreen = (BYTE)MulDiv(endGreen-startGreen, dn, length) + startGreen;
    		BYTE currentBlue = (BYTE)MulDiv(endBlue-startBlue, dn, length) + startBlue;
    
    		RECT currentRect = {0};
    		if (isVertical)
    		{
    			currentRect.left = rcGradient->left;
    			currentRect.top = rcGradient->top + dn;
    			currentRect.right = currentRect.left + rcGradient->right - rcGradient->left;
    			currentRect.bottom = currentRect.top + dy;
    		}
    		else
    		{
    			currentRect.left = rcGradient->left + dn;
    			currentRect.top = rcGradient->top;
    			currentRect.right = currentRect.left + dy;
    			currentRect.bottom = currentRect.top + rcGradient->bottom - rcGradient->top;
    		}
    
    		HBRUSH currentColor = CreateSolidBrush(RGB(currentRed, currentGreen, currentBlue));
    		FillRect(hdc, &currentRect, currentColor);
    		DeleteObject(currentColor);
    	}
    }
    
    
    /*  This function is called by the Windows function DispatchMessage()  */
    LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
    {
        RECT myRect;
        COLORREF startCol = RGB(71,71,71), endCol = RGB(200,200,200);
    
        switch (message)                  /* handle the messages */
        {
            case WM_DESTROY:
                PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
                break;
            case WM_ERASEBKGND:
                GetClientRect(hwnd, &myRect);
                GradientFillRect(HDC (wParam), &myRect, startCol, endCol, false);
                return 1;                           // indicate that WM_ERASEBKGND was handled
    
            default:                      /* for messages that we don't deal with */
                return DefWindowProc (hwnd, message, wParam, lParam);
        }
        return 0;
    }
     
    Question(WIN3204)How to change current working directory in C/C++?[Top]
    Answer_chdir [^].
    SetCurrentDirectory [^].
     
    Question(WIN3205)How to get my hard disk name and all the information related to it?[Top]
    AnswerYou can use WMI.

    Here is sample link for using WMI
    WMI C++ Example[^]

    And here is WMI class that you may be looking for with all the hdd information

    Win32_PhysicalMedia[^]
     
    Question(WIN3206)How to get LoginNames of all Users in my Domain?[Top]
    Answeryou can try NetUserEnum() or NetQueryDisplayInformation()
     
    Question(WIN3207)How can I get Temp Folder path?[Top]
    Answeryou can try GetTempPath() or SHGetSpecialFolder()
     
    Question(WIN3208)What is the easiest way to convert a CString into a standard C++ string?[Top]
    AnswerAn array of characters?
    CString CStr = ...;
    LPTSTR pTCharStr = new  TCHAR[CStr.GetLength() + 1];
    
    _tcscpy_s(pTCharStr, CStr.GetLength() + 1, CStr);
    
    Or an STL string?
    #include <string>...
    CString CStr = ...;
    #if defined(_UNICODE)
           wstring stdstr = CStr;
     #else
           string stdstr = CStr;
     #endif
    
     
    Question(WIN3209)How can I get the name of Win CE device?[Top]
    Complete QuestionI am working on windows moblie. Does there is any API to determine the name of device?
    Answeryou can try GetSystemInfo() or SystemParameters()
     
    Question(WIN3210)How can I catch a Windows PowerDown (or Hibernation) Event and Way to Disable it?[Top]
    AnswerYou have to wait for WM_POWERBROADCAST  in case of system powerdown and returning BROADCAST_QUERY_DENY from it would halt your system from shutting down
     
    Question(WIN3211)How can I check the existence of a Registry Key using C++?[Top]
    AnswerIf you want to check if a Registry key exists:
    HKEY hKey = NULL; 
    string MyChoiceVariable; 
    if (ERROR_SUCCESS != RegOpenKeyEx(
        HKEY_LOCAL_MACHINE, 
        "SOFTWARE\\..", 
        0,
        KEY_QUERY_VALUE,
        &hKey ))
     { 
      MyChoiceVariable = "KEY DOES NOT EXIST"; 
      
      cout << MyChoiceVariable << endl; 
     } 
     
     if (ERROR_SUCCESS == RegOpenKeyEx( 
        HKEY_LOCAL_MACHINE, 
        "SOFTWARE\\..", 
        0,
        KEY_QUERY_VALUE,
        &hKey ))
        { 
          MyChoiceVariable = "KEY EXISTS"; 
          cout << MyChoiceVariable << endl;
        } 
     
    Question(WIN3212)How to create Shared Files and Folders ?[Top]
    Complete QuestionI am writing an Installation Program, in which I create a number of Folders. Is there a way of ensuring that the Created folders are available Shared for read and write over the Network. It is assumed that the person performing the Installation has Administrator Rights.
    Answertry NetShareAdd() http://msdn2.microsoft.com/en-us/library/bb525384%28VS.85%29.aspx[^]
     
    Question(WIN3213)The coordinates are the client area, but arent correct if the window is being scrolled. What can i do ?[Top]
    AnswerAnswer 1:

    Use GetScrollInfo, add amount scrolled(lpsi->nPos) to retrieved client co-ordinates. Hope this helps!

    Answer 2:

    The scroll window has no actual relationship to window it is attached to. Take notepad for example. Every time you click on the up arrow on the scroll bar, the text moves by one line of text. So the amount of pixels will vary depending on the font size. Which won;t really be available to some external program. When a program uses scroll bars, and is asked to paint a window, it gets the scroll pos, and interprets that however it likes. And how they do it will be app dependent...

     
    Question(WIN3214)How to run dll using Rundll32.exe ?[Top]
    Answer

    To exploit the rundll32.exe your exported function must follow some rules, for instance the prototype must be like the following :-

    CALLBACK MsgBoxW(HWND hwnd, HINSTANCE hinst, LPWSTR lpszCmdLine, int nCmdShow); then a working sample (at least, on XP it works...) will be

    void CALLBACK MsgBoxW(HWND hwnd, HINSTANCE hinst, LPWSTR lpszCmdLine, int nCmdShow)
    { 
        MessageBox(hwnd, lpszCmdLine, L"MyMessageBox", MB_OK);
    }
    with def file LIBRARY "MyDLL"EXPORTSMsgBoxW @1 for a complete discussion see http://support.microsoft.com/?scid=kb%3Ben-us%3B164787&x=14&y=14[^]
     
    Question(WIN3215)How to detect user's language for user interface?[Top]
    Answer

    GetSystemDefaultLangID() returns the system locale. This is used to determine which code page is used for non-Unicode (aka "ANSI") text on a system. It can be changed (on XP) from the advanced tab on the "regional and language options" in Control Panel (probably needs to be rebooted before the change takes effect) GetUserDefaultUILanguage() returns the current UI language which can be set by a user if MUI pack is installed.

     
    Question(WIN3216)How to check process memory usage?[Top]
    Complete AnswerI am writing a multi-threaded program that will have to run continuously. Since the program uses a lot of memory allocations (next to my own allocations, MFC will also do some of that when using CStrings and all that) I want to be able to monitor the program's memory usage at any one given time. Does anyone know of a way to request the total amount of memory used by the program through some C++ statement(s), so that I can report this usage in a tracefile while the program is running.
    Answer

     Try GetProcessMemoryInfo()

      
      

    GENERAL

     
      
    Question(GEN01)How to call  a function in an external .js file from C++ ?[Top]
    AnswerFollowing links would help:-
     
    Question(GEN02)How can I get Total number of days of a Year.(wheter 365 or 366)?[Top]
    AnswerAnswer#1

    If the year is a multiple of 4, it's a leap year, i.e. there are 366 days.

    Exception #1:
    If the year is dividable by 100 it's not a leap year.

    Exception #2:
    If the year is dividable by 400 it's a leap year anyway.

    Hint: use the modulus operator.

    Answer#2
    C++
    bool isLeapYear(int year )
    {
     return year % 400 ? year % 100 ? year % 4 ? false : true : false : true;
    }
    
     
    Question(GEN03)How to develop windows system startup application?[Top]
    AnswerYou can read an article of Mark Russinovich from sysinternals at http://technet.microsoft.com/en-us/sysinternals/bb897447.aspx[^]
    and for an ex. you can download the source code of the program. you can find the source from web.archive.com http://web.archive.org/web/20060110210637/www.sysinternals.com/Information/NativeApplications.html[^]
     
    Question(GEN04)How to deploy executable build in VS2005?[Top]
    Complete QuestionI have build the Executable in Release mode , when I try to deploy in on target PC,
    I encounter Following Error "This application has failed to start because the application
    configuration is incorrect. Reinstalling this application may fix problem."
    AnswerPlease follow to this link :-
    http://msdn.microsoft.com/en-us/library/zebw5zk9(VS.80).aspx[^]
     
    Question(GEN05)How to get XP Style Look?[Top]
    Complete QuestionI've migrated from old VC++6 to VC++2005, I want XP look for my application
    AnswerThere are a lot of ways to make it work on VS2005 or 2008. This is mine:
    1. Add the InitCommonControls() call at the very beggining of your program.
    2. On the stdafx.h file, add this line: #include "commctrl.h" On the properties of your project:
    3. On Linker/Manifest File make sure the generate manifest entry is set to "Yes"
    4. On Linker/Command Line add "comctl32.lib" (without the cuotes).
    5. On Manifest Tool/Input and Output, set the "Aditional Manifest File" to $(IntDir)\XPCommonControls.manifest
    Finally create a new text file with this code and save it as "XPCommonControls.manifest" on the same folder than your .exe
    XML
    <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestversion="1.0">
         <dependency>
              <dependentassembly>
                   <assemblyidentity>
                        type="win32"
                        name="Microsoft.Windows.Common-Controls"
                        version="6.0.0.0"
                        processorArchitecture="X86"
                        publicKeyToken="6595b64144ccf1df"
                        language="*"/>
     
    Question(GEN06)How to convert the HEX format to human readable value?[Top]
    Complete QuestionI have a file which contains hex values. I want to convert that to human readable form.
    AnswerSupposing ANSI build and error handling left to the reader
    FILE * fpin = fopen("MyBinaryFile.foo","rb");
    FILE * fpout = fopen("MytextFile.txt","w");
    int c;
    int count = 0;
    while ( (c=getc(fpin)) != EOF )
    {
     fprintf(fpout, "%02x ", c);
      if (count % 16 == 15) fprintf(fpout, "\n");
    
     count++;
    }
    
    fclose(fpin);
    fclose(fpout);
    
     
    Question(GEN07)How can a program detect that the local computer is connected to a network ? [Top]
    AnswerPlease follow to this link :-
    http://www.pcausa.com/resources/InetActive.txt[^]
     
    Question(GEN08)I want built app to communication through USB port. How to start ?[Top]
    AnswerUSB FAQ[ http://www.lvr.com/usbfaq.htm[^] ]
     
    Question(GEN09)How to set an expiration date on an application or dll?[Top]
    Complete QuestionI want to create a free trial version of software that stops running after 30 days or whatever, how do I do that?
    AnswerThe simple way is:
    1. choose a place to store a date (registry, a file, etc)
    2. when the app starts, check that place for the date
    3. if you don't find a date, store the current date there
    4. if you do find a date, subtract the current date from the stored date.
    5. compare the difference to your time limit. there's a huge obvious vulnerability in schemes like this (find the date and erase it to reset the trial). but, they do work.
     
    Question(GEN10)Accessing with NULL pointer without crash?[Top]
    Complete Question

    Pls tell me how this program works... I set a pointer to class to Zero, but still I can access an instance member as far as I don't access any instance variable.

    #include "stdafx.h"
    #include <stdio.h>
    
    class A
    {
    public:
     int i;
     void PrintMe();
    };
     void A::PrintMe()
     {
      printf("Hello World\n");
     }
    
     void main()
     {
         A* p = 0;
         p->PrintMe();
     }
    
    AnswerAnswer#1:

    The A::PrintMe function doesn't access class members and isn't virtual so the this pointer isn't used. This is perfectly legal.

    Answer#2:

    Calling a method on p doesn't actually dereference p, it just sets this to the value of p. If PrintMe() dereferenced this, for example accessing non-static data members, then the code would crash.

     
    Question(GEN11)How do I declare initialise a global variable, exported from one dll and use it from various files? [Top]
    AnswerIn DLL:

    __declspec(dllexport) int g_iYourVariable;

    In EXE files:

    __declspec(dllimport) int g_iYourVariable;

     
    Question(GEN12)How to convert char arrays containing embedded NULL characters to BSTR?[Top]
    Complete Question

    I want to convert a char array containing embedded NULL(/0) chars to BSTR. eg cArr['1','2','NULL','3','NULL','4','5','NULL']. Is it possible to convert it to bstr without losing anything. So the _bstr_t variable will contain "12NULL3NULL45NULL"

    AnswerThe perfect way to do that is
     char cArr[] = { '1', '2', '\0', '3', '\0', '4',
    '5', '\0' };
    
    BSTR MyBstr = ::SysAllocStringByteLen(cArr, sizeof(cArr));
    _bstr_t  bstrSend(MyBstr, true);
    
     
    Question(GEN13)How to call .NET Managed DLL from Unmanaged codes?[Top]
    Complete Question

     I want to develop a dll in .Net to send email (using namespace System.Web.Mail),then i want to call it in MFC application. So i want to know whether is it possible to call .Net dll in MFC App??

    AnswerClick on this link http://support.microsoft.com/kb/828736[^]
     
    Question(GEN14)How to get project name at compile time?[Top]
    Complete Question

    Is there any possibility available to get the project name during the compile time? I need the project name as string.

    Answer
    1. Get the value of project name from the project property if you are using VS2005, vsproperty->c/c++->preprocessor->preprocessor definitions: PROJECT_NAME=$(ProjectName)
    2. Now use the PROJECT_NAME Macro from above in your code,
      #define STRINGIZE(_x) #_x
      #define STRINGIZEVALUE(_x) STRINGIZE(_x)
      
      char projectName[]= STRINGIZEVALUE(PROJECT_NAME);
      
     
    Question(GEN15)How to detect if pointer points to the stack or the heap?[Top]
    Complete Question

    I have a list (CList) of pointers. Some of them point to variables in the heap a some others not. I've defined a destructor that frees the memory space, but the program crashes when I delete a pointer to a variable in the stack.

    Answer

    // IsOnStack.cpp : Defines the entry point for the console application.//

    #include "stdafx.h"
    #include <iostream>
    #include <windows.h>
    using namespace std;
    
    bool IsOnStack(const void *pData)
    {
        DWORD StackBase;
        DWORD StackLimit;
        __asm {
                MOV EAX, DWORD PTR FS:[0x04]
                MOV StackBase, EAX
                MOV EAX, DWORD PTR FS:[0x08]
                MOV StackLimit, EAX
               }
    
        DWORD Address = reinterpret_cast<DWORD>(pData);
        return   (Address >= StackLimit) && (Address < StackBase);
    }
    
    const char* PrintStack(const void *pData)
    {
        return IsOnStack(pData) ? ": Stack" : ": Not on Stack";
    }
    
    int main(int argc, char* argv[])
    {
         const char *pString1 = "String1";
         cout << pString1<<
    
         PrintStack(pString1) << endl;
         char String2[] = "String2";
         cout << String2 <<
         PrintStack(String2) << endl;
         return 0;
     }
    

    Output is:
    String1: Not on Stack
    String2: Stack

     
    Question(GEN16)Is it possible to create an NFS mount in C++? [Top]
    Answer

    The phrase 'NFS mount' implies a device driver. It is generally not recommended to develop Microsoft Windows device drivers in C++ however it can be done. Microsoft supplies the IFS Kit[ http://www.microsoft.com/whdc/DevTools/IFSKit/default.mspx[^]] for developing file systems and file system filters.

    If you however simply want to use something already available (or have some common sense) then perhaps you can use Microsoft Windows Services for UNIX[ http://technet.microsoft.com/en-us/interopmigration/bb380242.aspx[^]] This link will give you a head-start.
    http://www.openfree.org/pet/index.php/Mount_an_NFS_share_from_Windows[^]

     
    Question(GEN17)What is the significance of #pragma once ?[Top]
    Answer

    #pragma once directive specifies that the file will be included only once by the compiler when compiling a source code file. This can reduce build times as the compiler will not open and read the file after the first #include of the module.

     
    Question(GEN18)How CWebBrowser2 can use Proxy ?[Top]
    Answer

    Application can use different proxy settings for InternetOpen instance

    (HINTERNET) using InternetSetOption. [ BOOL InternetSetOption( __in HINTERNET
    hInternet, __in DWORD dwOption, __in LPVOID lpBuffer, __in DWORD dwBufferLength
    ); ^]
    
    where hInternet, InternetOpen instance, if it is NULL, the scope of the settings is global
    and is default option settings for Internet Explorer. So it changes the settings for WebBrowser control
    as well as all instance if IE. If you want to specify proxy settings for your application alone with out
    changing the default settings, I don't know any interface exposed by WebBrowser control.But with some
    effort you can achieve that, you may open an HINTERNET, InternetOpen instance for your application with
    proxy settings, and download the URL file using [wininet APIs[ http://msdn.microsoft.com/en-us/library/aa385473(VS.85).aspx[^]]
    and display the html source in WebBrowser control. That is WebBrowser control is used for only rendering HTML and getting UI events, connection is handled by your program

     
    Question(GEN19)Vista elevation problem ?[Top]
    Complete Question

    When i run my program it gives an error "The requested operation requires elevation". my program compiles correctly but gives error at this time

    AnswerHave a look at the following links:
     
    Question(GEN20)How to read from bluetooth? [Top]
    Complete Question

     I've bought a simple bluetooth external device(like Asus WL-BTD201 Bluetooth dongle). I want to create a single program to read it but I haven't any idea what I need to do. Is there a free library that I can use? I've read something like bluetooth have a stack(???). Things like WIDCOMM stack. Honestly I have any idea how can I do this. Someone can help.

    AnswerBluetooth development kit[^]from Broadcom corporation is distributed free of cost.
      

    FUNNY

      
    Question(FUN01)How to scan or identify a physical damage (like scratch or spot) in a blank writable CD?[Top]
    AnswerYou will need a small cotton ball, a mild liquid soap, clean water and a table lamp.

    Add a few drops of the liquid soap in water, soak the cotton in the soapy solution and wipe the surface of the disc gently, rubbing the cotton back and forth against it in a rocking motion.

    Switch on the table lamp and let the light lit the surface of the CD. You will be able to spot scratches and physical damages on it easily now.

    BTW, this forum is for Visual C++ questions.
     
    Question(FUN02)How to display a messagebox after the application is closed ?[Top]
    To display a messagebox after the application is closed ?
    1. the message box when your application is still running.
    2. Press down the Print Screen key on the keyboard.
    3. Close your application.
    4. Open MS Paint.
    5. Paste the image ( CTRL + V ).
    6. Enjoy you Message Box
     
    Question(FUN03)On lighter side About Polymorphism![Top]
    Answer

    On lighter side About Polymorphism :-

    Teacher object calls the LearnPolymorphism() method on two instances of Pupil. The first one one,
    say cleverPupil, that is really an instance of CleverPupil, calls readBook(goodOOPBook) to fulfill task.
    On the other hand, the second Pupil instance, say lazyPupil, instance of LazyPupil, implements the method
    in his own way, with a call to startAsking(hereAndThere)...

    Both CleverPupil and LazyPupil inherit from Pupil hence Teacher is able to call virtual Pupil method
    LearnPolymorphism() on them. But, due to Polymorphism, Teacher obtains two quite distinct results from them.

      

    Experts

    <><>   
    Above Queries were answered by following experts:-
    • Rajesh R Subramanian
    • Roger Stoltz
    • cmk
    • CPallini
    • Michael Schubert
    • PJ Arends
    • ThatsAlok
    • DavidCrow
    • Naveen
    • Michael Dunn
    • cofi++
    • Moak
    • Mike O'Neill
    • SandipG
    • Mark Salsbery
    •  Alain Rist
    • J_E_D_I
    • Maxwell Chen
    • Iain Clarke
    • Nibu babu thomas
    • Rajkumar R
    • Stephen Hewitt
    • led mike

     

       

    Points of Interest

    Nothing much to say, idea and design are taken from Mr. Michael Dunn (MS Visual C++ MVP) CPP Forum FAQ article.

    Please keep in touch for more article on this series.

    Special Thanks

    • My Parents & My Wife
    • All active contributors/members of the Visual C++ forum [CodeProject], as without them this article wouldn't have seen day light.

    Other Articles of this Series

    History

    • 25 July 2010: Posted on CodeProject. (Yes it take 5 year to publish this article)
    • 11 July 2006: Started working on this article.

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)