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

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

4.81/5 (14 votes)
15 Jul 2011CPOL27 min read 33.3K  
Collection of Q&A from VC++ forum

Introduction

Nothing unusual & as Usual ... this article is a compilation of questions and answers which were asked on the Code Project Visual C++ forum. Also, this is the fourth 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 (my apology for same). If I have missed something, please feel free to mail me or leave a comment at bottom.

Content 


MFC

MFC01How to avoid Resource Conflicts in MFC Extension DLLs?
MFC02What is the max rows and max column size of the CListControl?
MFC03In List control, while using the Scroll bar, how we can know how much rows has went upside if scroling?
MFC04How to tile multiple windows in a single view?
MFC05How to find 2nd saturday of the month (using COleDataTime)?
MFC06How can remove dotted gray line that is display in row of ListCtrl?
MFC07What's the best method to get the currently active child frame window/ currently active view/ or document?
MFC08How to convert a CString value to HEX?
MFC09How can identify click on hashbutton or item label in Tree Ctrl?
MFC10What is the big difference between vectors and the CArray?
MFC11How to expand collapse a tree control all child items with a single function?
  

WINDOW32

 
Win3201How to solve this error information: "_WIN32_WINNT settings conflicts with _WIN32_IE setting" ?
Win3202Is there any API which i can import a registry file in the registry editor?
Win3203I need full control permission for everyone in HKEY_LOCAL_MACHINE, how can i get this through source?!
Win3204How to delete a file in AllUserProfile directory?
Win3205How to suspend the current application, till spawned process complete it task and exit?
Win3206How to set system font dialog with default font name and size?
Win3207How to get the system Clock Style, I mean weather it 12 hr clock style or 24 hr clock style?
Win3208How to log the start up and shut down time of all the PCs connected in a lan to a file?
Win3209How to remove maximize button from frame window in SDI application?
Win3210Is there any way other function which will allow to display custom progress bar during file copy?
Win3211How to Get the process ID and memory usage of self?
Win3212How to handle event across process?
Win3213How can find out that how thread running in my application ?
Win3214How to Load Dialog From a Resource DLL?
  

GENERAL

 
GEN01Is there any application that can retrieve class names for running window application?
GEN02Is there is UrlDownloadToFile() equivalent for linux?
GEN03What field of PE Header tells that whether a valid PE file or not?
GEN04What are the Major Changes, when moving from Visual C++ 6.0 to Visual C++ .NET?
GEN05How to delete a memory on Heap if it is holded by a reference ?
GEN06What is the unique in any pc?
GEN07how to split a DWORD value?
GEN08When moving from VS6 to Vs2005, what happen to Static Library?
GEN09 When moving from VS6 to Vs2005, what happen to Dynamic Link Library?
GEN10How to pass generic pointer to function with void** parameter?
GEN11Type Casting:I am always confused between static, dynamic, and reinterpret casting? please explain?
GEN12How to create a transparent window?
GEN13How to get serial number of motherboard using C++ on WINDOWS?
GEN14Which is better? Returning reference or value?
GEN15What is the difference between new and malloc function?
GEN16I created a new dialog resouce. Now I want to remove it from the project. How to do this?
GEN17What is difference between Inline and MACRO as speed and execution?
GEN18How to convert HEX to CString?
GEN19How to avoid namespace collision?
GEN20How to read Registry Windows 7 remotely?

FUNNY

 
FUN01I want to search music on the internet,but i don`t know how to do it?
FUN02 Not an answer to your question, but when you say "kindly bare with me"
FUN03Is it possible to write a code that adds today's date to a jpg photo?
FUN04I experienced that asynchronous disk io is not reliable. Am i correct?
FUN05 How to compare two audio file?
  
  

Answer

 

MFC

 
  
Question(MFC01)How to avoid Resource Conflicts in MFC Extension DLLs?
Complete QuestionOver the years I have written a number of MFC extension DLLs which, amongst other things, contain resources (mainly dialogs) which can be accessed from the main app as well as from code within the DLL itself.
Occasionally I ran into problems of the resource ID's clashing with those of the main app, and to avoid this, I have always tried to allocate resource IDs in different ranges in each DLL. This has worked OK but it is getting increasingly difficult to manage and I thought that there must be a more elegant way to ensure that you can access the correct resource.
AnswerI've been using AfxSetResourceHandle() for that. Call once before accessing a resource, and use it afterwards to reset the handle. Of course you will have to know what dll contains your resource. Depending on your architecture, this can be really simple, or close to impossible On way to solve some of these problems is to have factory functions exported from the dll for creating dialogs and such.
 
Question(MFC02)What is the max rows and max column size of the CListControl?
AnswerSince the documentation doesn't say anything about the maximum limits, I guess it would either depend on the available process memory or the maximum value an int can hold since the index is specified using an int variable.
 
Question(MFC03)In List control, while using the Scroll bar, how we can know how much rows has went upside if scroling?
Answerguessing that the list control is in report view, try handling LVN_ENDSCROLL notification from List control. Use GetTopIndex() to get the index of top visible item. That much rows will be on top.
 
Question(MFC04)How to tile multiple windows in a single view?
Answerthere are methods like CMDIFrameWnd::MDICascade and CMDIFrameWnd::MDITile that can do this for you. There are also APIs called CascadeWindows and TileWindows that can do the same thing.
 
Question(MFC05)How to find 2nd saturday of the month (using COleDataTime) ?
Answer Answer#1
  1. Set a COleDataTimeSpan object (day) to a day
  2. Set a COleDataTime object (date) to the desired month of the desired year
  3. Build a loop of the incrementation (date += day)
  4. while (1(sat) != date.GetDayOfWeek()) for two times
  5. Now you (date) are at the second sat
Answer#2
COleDateTime dt(year,month,1,0,0,0);
int add = 14 - dt.GetDayOfWeek();
dt += add;
 
Question(MFC06)How can remove dotted gray line that is display in row of ListCtrl?
AnswerThe dotted lines constructs the focus rectangle, which is vital information for someone using the keyboard to navigate the GUI. To get rid of it, you could Custom Draw[^] the list.
 
Question(MFC07)What's the best method to get the currently active child frame window/ currently active view/ or document?
AnswerHere is what we use in my MDI applications:
// First get the MDI frame window
CMDIFrameWnd* pFrame = (CMDIFrameWnd*)AfxGetApp()->m_pMainWnd;
 
// !Here we get the active MDI child window!
CMDIChildWnd* pChild = (CMDIChildWnd*)pFrame->GetActiveFrame();
 
// Alternatively you can use    
// CMDIChildWnd* pChild = pFrame->MDIGetActive();
       
// !Get the active view attached to the active MDI child window!
CMyView* pView = (CMyView*)pChild->GetActiveView();
 
// !Get the active document!
CMyDoc* pDoc = (CMyDoc*)pChild->GetActiveDocument();
 
Question(MFC08)How to convert a CString value to HEX?
Answer Answer#1
ULONG nVal;
CString str = _T("0x4335");
nVal = _tcstol(str, NULL, 0)
Answer#2
In C++ use the facilities of the Standard C++ Library:
#include <sstream>
int GetIntFromHexString(const char* HexString)
{
	int val;
	std::istringstream(HexString) >> std::hex >> val;
	return val;
}
 
Question(MFC09)How can identify click on hashbutton or item label in Tree Ctrl?
AnswerYou'll probably want to do something like this when handling the NM_DBLCLK notification:
case NM_DBLCLK:
	// Get the double clicked item
	HTREEITEM hItem = (HTREEITEM)SendMessage(((LPNMHDR) lParam)->hwndFrom,TVM_GETNEXTITEM,TVGN_CARET,0);
	TVITEM tvi;
	tvi.mask  = TVIF_PARAM;
	tvi.hItem = hItem;
	// Get the lParam value asociated with this item 
	SendMessage(((LPNMHDR) lParam)->hwndFrom,TVM_GETITEM,0,(int)&tvi);
	break;
tvi.lParam now contains the lParam value you added to the item when you added it to the tree view. You could use this value to give information on the content, e.g. if it is a hash button or item label.
 
Question(MFC10)What is the big difference between vectors and the CArray?
Answer Answer#1
It's a question of modernity; MFC collections are obsolete.

STL is the standard template library.
STL is faster (test in release, not debug mode) and offer more flexibility (algorithms, iterators, ...)

here's a link to a discussion :
http://www.codeguru.com/forum/archive/index.php/t-391319.html[^]

"...And frankly the team will give you the same answer. The MFC collection classes are only there for backwards compatibility. C++ has a standard for collection classes and that is the Standards C++ Library. There is no technical drawback for using any of the standard library in an MFC application. We do not plan on making significant changes in this area.

Ronald Laeremans
Acting Product Unit Manager
Visual C++ Team..."

Answer#2

As once said distinguished Mr. Grauss: "MFC containers are a crap".
I do believe he was right. STL container design is more rigorous and clean.
Now you feel more comfortable with CArrays, etc.., but, once get used with STL, you won't go back.
   
Question(MFC11)How to expand collapse a tree control all child items with a single function?
Answer CTreeCtrl::Expand[^] should do what you mean?
If you want to expand an item and expand all child items too, you'll have to loop through them.
  
 

WINDOW32

 
  
Question(WIN3201)How to solve this error information: "_WIN32_WINNT settings conflicts with _WIN32_IE setting" ?
Complete Question Now ,I want to convert the vc project to vs2008. when I complied this dll in vs2008: it throw this error code :
1>c:\program files\microsoft sdks\windows\v6.0a\include\sdkddkver.h(217) : fatal error C1189: #error : _WIN32_WINNT settings conflicts with _WIN32_IE setting
I search the macro "_WIN32_WINNT" in my project,but it isn't found defined this anywhere. Now I add this code in the "stdafx.h":
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif 
At last, I delete the new SDK Include path in the vs2008. but it failed too.
AnswerLooks like the compiler is mixing up files coming from different SDK versions. WINVER _WIN32_WINNT and _WIN32_IE should be defined so that the "components" are not newer than the API they run on. Just give a look to the order of the directory search (include, libraries, DLL etc. should refer to the various SDKs in the same order). Also, check if no ".h" file is missing in a new SDK (so that an older one is found in another)
 
Question(WIN3202)Is there any API which i can import a registry file in the registry editor?
AnswerRegLoadKey[^]
 
Question(WIN3203)I need full control permission for everyone in HKEY_LOCAL_MACHINE, how can i get this through source?!
Answer RegSetKeySecurity[^]
 
Question(WIN3204)How to delete a file in AlluserProfile directory?
Answer GetAllUsersProfileDirectory[^] simply gives you the path to the "All Users" folder, it doesn't delete anything, but i will assume you know that and you are simply asking how to use this function, something like this (not tested, error checking ommited):
DWORD charsNeeded;
GetAllUsersProfileDirectory(NULL, &charsNeeded); TCHAR *FolderPath = new
TCHAR[charsNeeded + 1]; GetAllUsersProfileDirectory(FolderPath, &charsNeeded);
... the path should be in the FolderPath buffer now, do whatever you want with it...
delete []FolderPath;
 
Question(WIN3205)How to suspend the current application, till spawned process complete it task and exit?
Answerthis code will help :-
int RunAppAndWait(char *cmd)  // where "cmd" is the command line with args
{
 PROCESS_INFORMATION ProcInfo;
 STARTUPINFO StartInfo;
 int exit_status = 0;
 
 memset(&StartInfo, 0, sizeof(StartInfo));
 StartInfo.cb = sizeof(StartInfo);
 if (CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &StartInfo,  &ProcInfo))
 {
  WaitForSingleObject(ProcInfo.hProcess, INFINITE); // wait for the command to finish
  GetExitCodeProcess(ProcInfo.hProcess, (unsigned long *)&exit_status);
  CloseHandle(ProcInfo.hProcess);
  CloseHandle(ProcInfo.hThread);
  return exit_status;
 }
 
 return 1;  // non-zero = failed
}
 
Question(WIN3206)How to set system font dialog with default font name and size?
Complete Questionwhen I call the system font dialog like this,how to set the default font name and size ?
HFONT FAR PASCAL MyCreateFont( void ) 
{ 
    CHOOSEFONT cf; 
    LOGFONT lf; 
    HFONT hfont; 
 
 
    // Initialize members of the CHOOSEFONT structure.  
    cf.lStructSize = sizeof(CHOOSEFONT); 
    cf.hwndOwner = (HWND)NULL; 
    cf.hDC = (HDC)NULL; 
    cf.lpLogFont = &lf; 
    cf.iPointSize = 0; 
    cf.Flags = CF_SCREENFONTS; 
    cf.rgbColors = RGB(0,0,0); 
    cf.lCustData = 0L; 
    cf.lpfnHook = (LPCFHOOKPROC)NULL; 
    cf.lpTemplateName = (LPSTR)NULL; 
    cf.hInstance = (HINSTANCE) NULL; 
    cf.lpszStyle = (LPSTR)NULL; 
    cf.nFontType = SCREEN_FONTTYPE; 
    cf.nSizeMin = 0; 
    cf.nSizeMax = 0; 
 
 
    // Display the CHOOSEFONT common-dialog box.  
    // How to set the defalut font name or size before call this function??? 
    ChooseFont(&cf); 
 
 
    // Create a logical font based on the user's  
    // selection and return a handle identifying  
    // that font.   
    hfont = CreateFontIndirect(cf.lpLogFont); 
    return (hfont); 
} 
AnswerIf you set the ... flag in the Flags member and initialize the other members, the ChooseFont function initializes the dialog box with a font that matches ...
 
Question(WIN3207)How to get the system Clock Style, I mean weather it 12 hr clock style or 24 hr clock style?
Answer Answer#1:
The system clock does not have a style it is merely a counter used to calculate the current time since some predefined date. However any clock displays used in Windows will access the regional settings to determine how such times should be displayed. I am not sure of the simple way to access the details but you could take a look at the
HKEY_CURRENT_USER\Control 
    Panel\International
registry key.

Answer#2:try it
bool GetTimeFormattedBySystem(const SYSTEMTIME& sSomeTime,
                              CString& cszReceiver)
{
  static const int iTimeStrLen(40);
  static TCHAR szResult[iTimeStrLen];
  
  cszReceiver.Empty();
 
  if (GetTimeFormat(LOCALE_USER_DEFAULT,
                    0,
                    &sSomeTime,
                    NULL,
                    szResult,
                    iTimeStrLen)) {
    cszReceiver = szResult;
  }
 
  return (0 < cszReceiver.GetLength());
}
Answer#3:
Have you tried GetLocaleInfo(LOCALE_ITIME)?
 
Question(WIN3208)How to log the start up and shut down time of all the PCs connected in a lan to a file?
AnswerYou need to go each pc one by one, these are the pointer which may help you in securing the startup and shutdown time :- For monitoring when a PC is started up, you'll need a service. For shutting down, you'll need to respond to the WM_ENDSESSION message.
 
Question(WIN3209)How to remove maximize button from frame window in SDI application?
Answer Answer#1
Don't set (or remove ) the WS_MAXIMIZEBOX style. As Ash said, the maximize box will then be drawn disabled. If you have none of WS_MAXIMIZEBOX and WS_MINIMIZEBOX styles, no size boxes are drawn at all.

Answer#2

Adjust the styles[^] in your CreateWindowEx() call so that the WS_MAXIMIZEBOX value is not included. If you are using MFC then I think you may need to do this within your PreCreateWindow() method in your CMainFrame class.
 
Question(WIN3210)Is there any way other function which will allow to display custom progress bar during file copy?
AnswerThe CopyFileEx[^] supports a progress callback.
 
Question(WIN3211) How to Get the process ID and memory usage of self?
AnswerYou could use the GetCurrentProcess[^]function and pass it to GetProcessMemoryInfo[^].
HANDLE hProc = GetCurrentProcess();
PROCESS_MEMORY_COUNTERS_EX info;
info.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
GetProcessMemoryInfo(hProc, (PROCESS_MEMORY_COUNTERS*)&info, info.cb);
 
Question(WIN3212)How to handle event across process?
AnswerHave a look at the functions CreateEvent, <code>SetEvent and WaitForSingleObject.
 
Question(WIN3213)How can find out that how thread running in my application ?
AnswerSee here[^].
You can use the code from the link, just need to replace the printf call with conditional check - if the process ID matches your own process ID, obtained via GetCurrentProcessId[^].
 
Question(WIN3214)How to Load Dialog From a Resource DLL?
Answer Firstly you need a message handler, essentialy the same as your main message handler, usually WndProc
BOOL CALLBACK DlgProc(HWND hDlg, UINT nMessage, WPARAM wParam, LPARAM lParam) {
	switch (nMessage) { 
		case WM_INITDIALOG: 
			//This is where you do all your initialisation. This is the first place after all the controls have been created, so you can use GetDlgItem()
			return TRUE; 
 
		case WM_COMMAND:
			//This is the same as it is in the WndProc, handle button clicks, etc...
			switch (LOWORD(wParam)) {
				case IDOK: //This is usually the OK or Done button
					return TRUE; 
 
				case IDCANCEL: //This is usually the Close or Cancel button
					DestroyWindow(hDlg); //close the dialog
					return TRUE;
			}
			break;
            } 
    } 
    return FALSE; 
} 
Then you just need to use that as the "procedure function"
void DisplayDynamicDialog(HWND hParent) {
	HMODULE hModule = LoadLibrary("Resources.dll");
	if(hModule != NULL) {
		hDialog = CreateDialog(hModule, MAKEINTRESOURCE(ID_DIALOG), hParent, (DLGPROC)DlgProc); 
		ShowWindow(hDialog, SW_SHOW);
		FreeLibrary(hModule); //This might need to be called later, after the dialog has been closed since it is modeless
	}
}
Finally,the ID you supply needs to be the ID defined in the DLL, not the ID defined in the exe, hence the resource.h that you include needs to be from the dll. To avoid confusion, I recommend using quoted string names instead.
 
  

GENERAL

 
  
Question(GEN01)Is there any application that can retrieve class names for running window application?
Answerspy++ application can get you the class name, for more info MSDN[^]
 
Question(GEN02)Is there is UrlDownloadToFile() equivalent for linux?
AnswerIt may not be as easy to use but on the CURL website there's a simple HTTP[^] client in about 6 lines. Open a file to write to and use CURLOPT_WRITEDATA and snip snip, bob's your Aunty:
#include stdio.h
#include curl
 
int main(void)
{
  CURL *curl = curl_easy_init();
  FILE *output_to = fopen( "output.txt", "w" );
 
  if( curl && output_to )
  {
    curl_easy_setopt(curl, CURLOPT_URL,       "curl.haxx.se" );
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_to      );
    curl_easy_perform(curl);
  }
 
  if( curl ) curl_easy_cleanup(curl);
  if( output_to ) fclose( output_to );
}
Bundle that lot up in a function and you're done...
 
Question(GEN03)What field of PE Header tells that whether a valid PE file or not?
Answeryou can follow this Wikipedia Link[^] to read more about PE header
 
Question(GEN04) What are the Major Changes, when moving from Visual C++ 6.0 to Visual C++ .NET?
AnswerI know it's kinda old, however people still use it, follow this link[^]
 
Question(GEN05)How to delete a memory on Heap if it is holded by a reference ?
Complete QuestionIf I can delete a memory using delete keyword for memory allocated on heap using new keyword.
class A
{
} ;
A &a1 = * (new A ) ;
How to release memory which is holded by a reference.
Answerdelete &a1 is exactly what he has to do.
It works perfectly. It may sound unorthodox, but depends how a1 is used: if a1 participate into arithmetic expression of overloaded operators inside generic code, it cannot be a pointer, and *a1 may be not suitable for template function expecting references.

Generic programming changes a lot the "traditional rules". (Note: you can also have a nullable reference as *(A*)0 that can be checked as !&a).
 
Question(GEN06)What is the unique in any pc?
AnswerThere are a number of different schemes used to implement this kind of protection, typically known as HWID (hardware id). Often a number of pieces of information are collected about various pieces of hardware before a transformation/hashing routine is applied to the result. An obvious downside to this method is that if any of the user's hardware changes, the generated HWID is also different - leading of course to the software having the impression that it's now on a different machine (well, it is in a sense - but not entirely)

Microsoft has relied upon a technique whereby the info collected from _each_ device is stored and compared at runtime. So long as a certain proportion of the IDs remain the same, the software will continue to run. Remember that Windows 95 (or thereabouts - perhaps it was XP, I forget) had some teething problems early on, with users reporting that windows would now refuse to run after small upgrades - this may have been simple incompatibilities, though if(!) my memory serves me correctly there were a large proportion that were a result of simple HWID authentication failure.

I believe microsoft has a patent for this kind of idea - one that allows a proprtion of the hardware to change, yet still pass authentication. ZBrush3 was software that implemented a similar scheme - albeit with a '1 change = authentication failure' limitation. You may find some interesting result Here[^].

You'll also find a lot of information on defeating these schemes in underground cracking/hacking sites - certainly good reading to determine how _not_ to implement this idea. (Tuts4You is a good site to check)
 
Question(GEN07)How to split a DWORD value?
Complete QuestionI have a DWORD data item and I want to make use of that as a 24 bit value and an 8 bit value. What would be a nice way of getting and setting the DWORD from two other variables?
AnswerYes, don't go in for complex mathematical expressions, even though the compiler will optimise them. Reread the previous answer and adjust for whichever part is the 8-bit and whichever is the 24-bit. In either case just use simple shifts AND and OR operators thus:
DWORD dwValue = (bits8 << 24) | bits24;
// or
DWORD dwValue = (bits24 << 8) | bits8;
And to split
bits8 = dwValue & 0xFF;
bits24 = dwValue >> 8;
// or
bits24 = dwValue & 0xFFFFFF;
bits8 = dwValue >> 24;
 
Question(GEN08)When moving from VS6 to Vs2005, what happen to Static Library?
Complete QuestionIf there is any static library built with older version of VS6.0, then it will not work correctly with an application built with VS2005. We need to rebuild it with the same compiler as the application is built with. Is this true? why this happens in case of static libraries
Answer Answer#1: yes. static libraries are almost never compatible between different versions of MS compilers. things like STL and MFC change between versions, interfaces break, members move around, etc..

Answer#2: if your library or DLL has a C interface and your programming language can use libraries or DLLs with a C interface then you can probably get away with mixing compiler versions. This is especially true for DLLs that you load manually
 
Question(GEN09)When moving from VS6 to Vs2005, what happen to Dynamic Link Library?
Complete QuestionIF Gen08 is true, then isn't it necessary to rebuild DDLs also with VS2005? If no, then why it is ok that a DLL built with older version of compiler works fine with application built with newer compiler version
AnswerAnswer#1: That depends on what kinds of things your DLL uses in its exported interfaces

Answer#2:
f your library or DLL are written in C++ make sure you compile your application with the same version of the compiler. Name mangling, object layout and loads of other things change from compiler version to compiler version. As well make sure you compile with as many identical compiler switches to avoid anything a bit weird sneaking in knackering your build. So this means that I can use a VC 6 C library from a VC2010 C++ application (I had to generate a new import library from the DEF file) but there's no way I could use static libraries from even VC++2008.
 
Question(GEN10)How to pass generic pointer to function with void** parameter?
Complete Question
int CreateArray(void** data, unsigned int* size)
{
//allocates some array and assigns it to data
}
 
int main()
{
unsigned char* data = 0;
unsigned int size;
int res = CreateArray(&data, &size);
}
Is it possible to avoid void* pData in main function and pass directly data pointer?
Answer
int res = CreateArray((void **) &data, &size);
 
Question(GEN11)Type Casting:I am always confused between static, dynamic, and reinterpret casting? please explain?
Answerstatic_cast and reinterpret_cast work in the same way than the classic C-style cast, but they are used in two different context:
  • static_cast is used when casting between two related types, for instance from a numeric type to another. The conversion could generate a loss of data, but without the cast operator the code compile; the compiler could generate a warning.
    char a, b;
    int x = 123;
    double y = 123.456;
    a = static_cast<char>(x); // From int to char
    b = static_cast<char>(y); // From double to char
    </char></char>
  • reinpterpret_cast is used when casting between two unrelated types, usually pointers, for instance from a pointer to a struct to a pointer to char. Without the cast operator the code doesn't compile; the compiler generate an error.
    POINT pt = { 10, 21 };
    unsigned char *pb = reinterpret_cast<unsigned>(&pt);
    // Print to screen the content of the structure in raw format
    for(int i = 0; i < sizeof(POINT); i++)
       printf("%02X  ", pb[i]);
       </unsigned>
Finally, dynamic_cast is a polymorphic cast operator; it's used only with pointers, and its main property is that if the conversion is possible it return the pointer value, otherwise it returns NULL. It's useful when working with inheritance.
 
Question(GEN12) How to create a transparent window?
Answer http://msdn.microsoft.com/en-us/library/ms997507.aspx[^]
 
Question(GEN13)How to get serial number of motherboard using C++ on WINDOWS?
Answer You can utilize services of WMI for getting serial number of mother board, the DeviceID property of the Win32_MotherboardDevice class bring the serial number and HERE[^] is example of using WMI in C++
 
Question(GEN14)Which is better? Returning reference or value?
Complete Question what do you think which of these would generate a faster way -if there's a difference at all- to query a class variable:
//--- Method A ----
class CMyClass
{
protected:
  int m_myVar;
 
public:
  int GetVar() const { return m_myVar; }
};
//---- Method B ----
  ...
  const int &GetVar() const { return m_myVar; }
  ...
//--- Method C ----
  ,,,
  inline int GetVar() const { return m_myVar; }
  ...
//---- Method D ----
  ...
  inline const int &GetVar() const { return m_myVar; }
  ...
Answer Answer#1
In your example you are returning a basic datatype (an integer), then it's quite the same to return by reference or by value: for example on a 32 bit environment, returning by reference means load the address of m_myVar inside the eax register, while returning by value means load the content of m_myVar inside that register.
The inlined versions of your methods could potentially be better, because the compiler could better optimize the usage of CPU registers and produce a code a bit more efficient. If your methods return a class or a struct the things could be different: returning by value means that your methods should allocate a temporary object on the stack and call its copy constructor. Then returning by reference in most of cases is better.

Answer#2
Actually in the long run, return by value may be shorter, but it depends on what you are measuring. For basic data types, the actual return doesn't make much difference, but then when you go to use the returned value, if it is returned by reference, there is an extra level of indirection to resolve. Of course what the compiler optimizes out and what else you might do with the results enters into the overall performance, so it's not a simple matter to determine a priori. However, in most cases, I doubt the difference is major.
 
Question(GEN15)What is the difference between new and malloc function?
Answer Answer#1
Short answer: new gives a chance for objects initialization (by calling constructors) and cleanup (delete calls destructors) while malloc provides bare allocation functionality.
Short advice: while doing C++ development always use the new/delete approach.

Answer#2
new creates new objects, malloc just reserves you a lump of memory and gives you a pointer to it. So when you say:
foo *p = new foo;
you're asking the compiler to generate the code for creating an original instance of foo (whatever that is) and to tell you where it is in the program's address space. Generally this means: - The compiler generates code for reserving a lump of memory to store the object in - It calls the appropriate constructor for foo and runs it on that lump of memory. On the other hand when you say (in C):
foo *p = malloc( sizeof( foo ) );
you're saying "give me a lump of bytes that happens to be the size of a foo and I'll treat it as a foo." There can be any old rubbish in there. If you want it initialised into any reasonable state you've got to do it manually. Incidentally this is one of the reasons you'll find C programmers immediately memsetting allocated memory blocks or using calloc instead - it gets the memory into a known state. You'll also find that many decent C programmers bundle allocation and initialisation into functions and call them things like "construct_foo" to keep the operation atomic.

Incidentally there are loads of places you can plug into the object creation sequence process in C++ but very few (i.e. none I know of) of modifying the way malloc works in C. In C++ you can modify how the memory is reserved (by overloading operator new or using placement new), what to do if the allocation fails (set_new_handler) and how the object is initialised (by writing constructors).

One final point. If new fails it throws an exception and winds back any initialisation or memory reservation that's already been completed. The exception is either bad_alloc if the memory reservation fails, or something from the constructor. If malloc fails it returns a NULL pointer, which is another good reason to use initialisation functions in C - you can handle all the errors in one place.
 
Question(GEN16)I created a new dialog resouce. Now I want to remove it from the project. How to do this?
Answer Just select that dialog (IDD_DIALOG1)in Resource view and press the delete button. Thats it...
 
Question(GEN17)What is difference between Inline and MACRO as speed and execution?
Answer Answer#1
There are two ways of getting a function expanded inline:
  • explicitly qualify it's definition with the inline keyword
  • define a function in the body of a class
In both cases it's at the discretion of whoever wrote the compiler. If their cost/benefit analysis reckons there's no gain to be had by inlining the function the compiler won't do it. [Likewise there's no reason why a compiler and linker can't conspire to do inlining across modules - VC++ has done that for years...]

Personally I only ever use inline functions when writing templates, otherwise I don't bother so the size of the functions that may or may not be inlined is a problem for someone else. Likewise with macros - I only ever use them if there's no other option within the programming language. Inline functions are usually a better bet as they're processed by the compiler and it can give you far more meaningful error messages than the preprocessor does. Execution speed wise it's impossible to say in the general case.

Answer#2
The Macro is dealed with the preprocessor, it is only text replace. Because the C language does not have const keyword. so coder uses the Macro to define the const. And the function defined too. The head file can use #define to define a macro to forbide one head file included more than once in a project. Now the Visual studio 2005 can use #pragma once instead of it.

The preprocessor cannot check the Macro type. so some error happens because for the Macro.
The inline can let function defined inside class.

Because one function called, it need to do jump, push stack, pop stack operations. So if some function simplely processes data and is called frequently, you can define this function as inline function to reduce the time used to call method. The incline funciton will be expansion by processor in the function called position. After compiled, you cannot find the inline function name.

I use inline function to cout the size of a struct.
About the speed, I donot test which is more quickly. But the c++ suggests not to use the macro. It often leads to error.
 
Question(GEN18) How to convert HEX to CString?
Answer You can do this easily using std::ostringstream[^].
Here is a small example for you:
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>

int main()
{	
	// Test numbers - num1 declared as HEX,  num2 as DEC
	const unsigned int num1 = 0x1234, num2 = 1234;
 
	// We will use std::ostringstream for the conversion
	std::ostringstream oss;
	
	// First num to Hex
        // "0x" is optional if you don't need it you can use "oss << std::hex << num1;"
	oss << "0x" << std::hex << num1; 
	std::string strFirstNumHex = oss.str();
        // Clear the content of the string buffer for later use
	oss.str(std::string());
 
	// Second num to Hex
        // "0x" is optional if you don't need it you can use "oss << std::hex << num2;"
	oss << "0x" << std::hex << num2;
	std::string strSecondNumHex = oss.str();
        // Clear the content of the string buffer for later use
	oss.str(std::string());
 
	// First num to Dec
	oss << std::dec << num1;
	std::string strFirstNumDec = oss.str();
        // Clear the content of the string buffer for later use
	oss.str(std::string());
 
	// Second num to Dec
	oss << std::dec << num2;
	std::string strSecondNumDec = oss.str();
	
	// This line prints: Numbers in HEX: 0x1234, 0x4d2       Numbers in DEC: 4660, 1234
	std::cout << "Numbers in HEX: " << strFirstNumHex << ", " << strSecondNumHex << "\t"
	          << "Numbers in DEC: " << strFirstNumDec << ", " << strSecondNumDec;
 
	std::cin.get();
	return 0;
}
As you can see from the above example strFirstNumHex and strSecondNumHex contain hex string representations of the test integers (strFirstNumHex = 0x1234 and strSecondNumHex = 0x4d2). strFirstNumDec and strSecondNumDec contain decimal string representations of the test integers.

If you don't need the "0x" prefix for your Hex strings you can remove this prefix from specified lines in above example. I hope this helps.

NOTE: For clearing the content of the stream buffer I usually use: oss.str("");, but it messes the formatting of the code block and I changed it to oss.str(std::string());.
 
Question(GEN19)How to avoid namespace collision?
Complete Question I am using 2 dlls which are having two namespace with the same name in it. If we import these two dlls in a new class and tried to access a variable in any one of the namespace from those 2 dlls, Will there be any namespace collision? if yes how can I avoid that
Answer rename_namespace attribute
rename_namespace("NewName")
NewName: The new name of the namespace. The rename_namespace attribute is used to rename the namespace that contains the contents of the type library. It takes a single argument, NewName, which specifies the new name for the namespace.
To remove the namespace, use the no_namespace attribute instead.

read more Here[^]
 
Question(GEN20)How to read Registry Windows 7 remotely?
AnswerMake sure that the Remote XP machine doesn't disabled the Remote Registry service locally via the Windows Services MMC, then you can use basic registry function to read registry values!
  

FUNNY

  
Question(FUN01)I want to search music on the internet,but i don`t know how to do it?
Complete Question I want to finish functions which can download music files from the internet, such as: I want to search the song named "yesterday once more", the I can get many links which can download this song. so it will be difficult for me to search the song and get the url of it. can anyone tell me how to accomplish this task?
AnswerTry using a search engine.
 
Question(FUN02)Not an answer to your question, but when you say "kindly bare with me"
AnswerNot an answer to your question, but when you say "kindly bare with me" it sounds like you're asking the reader to get naked with you.
You need to use the spelling "bear" which means the big fuzzy ursine critters as well as carrying something. It's an easy mistake to make - quite a few Americans I know keep saying they support the right to bare arms, which is fairly non-controversial if you use sun-screen.
 
Question(FUN03)Is it possible to write a code that adds today's date to a jpg photo?
Answer
  1. read JPG without date
  2. draw the date text onto the image
  3. save the image as a new JPG
  4. wait 23.9999999 hours
  5. goto 1
there are a million ways to do 1, 2 and 3.
Question(FUN04)I experienced that asynchronous disk io is not reliable. Am i correct?
Answer It is known to occasionally return bits that are neither one nor zero.
   
Question(FUN05)How to compare two audio file?
Answer I think I've heard this question before. I wonder how I can compare them
  

Experts

Above Queries were answered by following experts(In alphabetical order):-
  • Aescleal
  • Alain Rist
  • CPallini
  • DavidCrow
  • Iain Clarke
  • J_E_D_I
  • Jackson2010
  • Mark Salsbery  
  • Maxwell Chen
  • Michael Dunn
  • Michael Schubert
  • Mike O'Neill
  • Moak
  • Naveen
  • Nibu babu thomas
  • Niklas Lindquist
  • Nuri Ismail
  • PJ Arends
  • Rajesh R Subramanian
  • Rajkumar R
  • Randor
  • Richard MacCutchan
  • Roger Stoltz
  • SandipG
  • Sauro
  • Stephen Hewitt
  • ThatsAlok
  • Thaddeus Jones
  • Viti
  • cmk
  • cofi++
  • emilio_grv
  • led mike
  • «_Superman_»

   

Special Thanks

  • My Parents, My Wife & Parkhi!
  • 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

  • 12 July 2011: Posted on CodeProject.
  • 11 May 2011: 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)