Click here to Skip to main content
15,881,588 members
Articles / Programming Languages / Visual C++ 10.0

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

Rate me:
Please Sign up or sign in to vote.
4.77/5 (12 votes)
26 Jun 2012CPOL25 min read 29.4K   27   1
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

MFC01 What are the recommendations for Choosing a Collection Class ?
MFC02 I need to implement hover effect on a button, tell me how?
MFC03 How can I programmatically set the size of that popup box?
MFC04 How to get the title text CTabCtrl's tabs?
MFC05 how to get CString::Format to make a 12,345.00 format (i.e. Number with comma)?
MFC06 How to add or delete propertypage to or from propertysheet, after domodal been called?
MFC07 How to set/remove ES_READONLY style of CEdit at runtime?
MFC08 What is StdAfx.h and Why should I use it?
MFC09 Difference between CDialog OnCreate vs OnInitDialog?
MFC10 How to remove warning "unused parameters" ?
MFC11 Has anyone attempted to use this CMFCMaskedEdit class and call GetWindowTextLength() to see if the control has any user-typed text in it?
   

WINDOW32

 
Win3201 How to programmatically differentiate between cd drive and dvd drive without a disk media inserted?
Win3202 How to create virtual registry?
Win3203 A question about FreeLibrary?
Win3204 How to disable the 'Alt' key System wide?
Win3205 What is the differences Between CreateWindow() and CreateWindowEx?
Win3206 How to Get GUID for DosDevice?
Win3207 How can i get the WM_MINIMIZE message of console window?
Win3208 How to get the main thread ID of a process (known by its ID) ?
Win3209 How do we determine the base address of a loaded DLL?
Win3210 How to tell the system to load a DLL at a base address that I specify?
Win3211 How can I check if window is hidden by another window?
Win3212 Difference between dynamic linking vs dynamic loading ?
Win3213 Is there a way to prevent the user from logging off from their Windows account while my application is running?
   

GENERAL

 
GEN01 Shall I use destructor in a pure virtural class?And when?
GEN02 I have a varibale of 8 bytes (ULONGLONG). How to extract first 6 bytes from that?
GEN03 Can you please tell me if there is any particular reason why the following operators can't be oveloaded.?
GEN04 Pop up like windows media player minibar(when minimised)?
GEN05 How can a program know if "Microsoft Visual C++ 2010 Redistributable Package (x86)" is installed?
GEN06 How to read a UDF format file?
GEN07 Simulating DOS 6.12 enviornment on Window 7?
GEN08 What is the return type of a value that is in degrees minutes seconds format?
GEN09 Copying text to the clipboard?
GEN10 How to restrict an object being allocated on the heap?
GEN11 What is the GUID for " Text transfer" in BlueTooth?
GEN12 How to get all Active Windows Com Port?
GEN13 My process should not get killed using Taskmgr?
GEN14 difference between strcpy_s vs StringCchCopy?
GEN15 Multilevel inheritance with Pure virtual function?
GEN16 How To Find String Literals?
GEN17 Why c++ doesn"t have virtual constructor?
GEN18 What is an interrupt number?What is AX register?
GEN19 How to convert double to BSTR?
GEN20 Where can I get WinUSB.sys and WinUSB.dll?
GEN21 Please provide cross-casting practical code?
GEN22 Why "var" prints "Whats up" instead of "newval"?
   

FUNNY

 
FUN01 Kundali match making algorithm?
FUN02 Solution for water pot problem?1
FUN03 How UnRAR a rar file with password ?
   
   

Answer

 

MFC

 
   
Question(MFC01) What are the recommendations for Choosing a Collection Class ?
Answer Please check this page on MSDN site
 
Question(MFC02) I need to implement hover effect on a button, tell me how?
Answer You have to call the TrackMouseEvent function which is usually in the WM_MOUSEMOVE handler. Here is an example - http://blogs.msdn.com/b/oldnewthing/archive/2003/10/13/55279.aspx
 
Question(MFC03) How can I programmatically set the size of that popup box?
Answer There's a few ways:
  • Set the size when you call Create() on the dialog.
  • Change the size using SetWindowPos()
  • Change the size using MoveWindow() 
 
Question(MFC04) How to get the title text CTabCtrl's tabs?
Complete Question The following code is crashing at the last line:
TCITEM tcItem;
tcItem.mask = TCIF_TEXT;
m_ReportTabCtrl.GetItem(ID_PANE_FOUND, &tcItem);
CString csText = tcItem.pszText;
Answer You did not initialise your TCITEM structure properly; see the MSDN documentation here. It would be better to check the return value from all Windows function calls rather than just assuming that they have succeeded.
 
Question(MFC05) How to get CString::Format to make a 12,345.00 format (i.e. Number with comma)?
Answer Consider using the API GetNumberFormat().
 
Question(MFC06) How to add or delete propertypage to or from propertysheet, after domodal been called?
Answer

In your Button Event handler on the PropertyPage, just call the parent PropertySheet "RemovePage()" function, for example, "RemovePage(this)". Be careful that if you are removing the active page, which you most likely are, you should use the PropertySheet function "SetActivePage()" to have some other page become active, like your welcome page.


I also use the CTreePropSheet class, or one of its derivations, and I remember that there was some issue with deleting pages and having the tree redrawn properly. I would test this with the standard CPropertySheet first, watching the tabs appear and disappear properly first, then move back to the CTreePropSheet class.

 
Question(MFC07) How to set/remove ES_READONLY style of CEdit at runtime?
Answer you can try ModifyStyle(), or SetReadOnly()
 
Question(MFC08) What is StdAfx.h and Why should I use it?
Answer Precompiled headers are used to reduce the compile time by adding often required include files there. browse http://en.wikipedia.org/wiki/Precompiled_header  ,

I would recommend, that you add the include files that most of your other application code requires to the stdafx.h. This significantly reduces the time to build your project.
 
Question(MFC09) Difference between CDialog OnCreate vs OnInitDialog?
Answer OnCreate is called just when the application requests that the Create function be called. So it is not guarenteed that the window is fully created.
OnInitDialog
is called after the window (in this case the dialog) is completely created.
When you are dynamically creating a control, you will specify its parent window handle and so it has to be created completely. So always do it in OnInitDialog as said in the previous answer.
 
Question(MFC10) How to remove warning "unused parameters" ?
Answer Either of the following methods will remove the warning -
void MyClass::reset(ErrorType)
{
}
OR
void MyClass::reset(ErrorType error)
{
error;
}
Or you can use the UNREFERENCED_PARAMETER macro which does the same as the second method -
void MyClass::reset(ErrorType error)
{
UNREFERENCED_PARAMETER(error);
}
   
Question(MFC11) Has anyone attempted to use this CMFCMaskedEdit class and call GetWindowTextLength() to see if the control has any user-typed text in it?
Answer

When MFC controls exhibit strange behavior I always take a look at the source code for the control located in the \VC\atlmfc\src\mfc installation path.


If you look at the Microsoft implementation within afxmaskededit.cpp you will find that the CMFCMaskedEdit class handles the WM_GETTEXTLENGTH, WM_GETTEXT and WM_SETTEXT messages overriding the default CWnd behavior.

The CMFCMaskedEdit class is actually returning the length of an internal CString buffer in response to the WM_GETTEXTLENGTH message. Therefore the Microsoft documentation that states: 'EN_CHANGE notification code is sent when the user has taken an action that may have altered text in an edit control. Unlike the EN_UPDATE notification code, this notification code is sent after the system updates the screen.' would not apply to this particular window class. Unfortunately you will have to implement something outside the box here. A couple of ideas:

Option [1]
Highlight all of the code in afxmaskededit.cpp and afxmaskededit.h and copy/paste into DavidCrowsMaskedEdit new class and change/improve the behavior.

Option [2] You could override PreTranslateMessage and check for the WM_KEYUP message belonging to the CMFCMaskedEdit control. Once the control has recieved this message... the CMFCMaskedEdit should have updated its internal buffer because it does its filtering in response to the WM_CHAR message. Note that this method will not handle copy/cut/paste from the clipboard so your mileage may vary.

BOOL YourMaskDlg::PreTranslateMessage(MSG* pMsg)
{
if(WM_KEYUP == pMsg->message)
{
if(::GetDlgCtrlID(pMsg->hwnd) == m_YourMaskEdit.GetDlgCtrlID())
{
int iLength = m_YourMaskEdit.GetWindowTextLength();
	
if(iLength)
{
	CString str;
	m_YourMaskEdit.EnableGetMaskedCharsOnly(TRUE);
	m_YourMaskEdit.GetWindowText(str);
	str.Remove(_T('_'));
 
	BOOL UserAddedText = str.GetLength();
}
}
}
return CDialog::PreTranslateMessage(pMsg);
}
Option [3] You could actually get the window text or text length in your WM_CTLCOLOR handler. Something like:
HBRUSH YourMaskDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
 
if(pWnd->GetDlgCtrlID() == m_YourMaskEdit.GetDlgCtrlID())
{
//Check to see if user added some text
}
return hbr;
}
I know it seems like a complete hack... by looking at window text in the WM_CTLCOLOR handler but that is actually how Dr. Joseph Newcomer did it in his old validating CEdit class. That is really all I can think of for solving your problem.

To be honest I generally avoid many of the MFC classes... I usually reinvent the wheel... because sometimes my wheels are more round. And if my new wheel ends up square... well at least I learned something in the process.
   
 

WINDOW32

 
   
Question(WIN3201) How to programmatically differentiate between cd drive and dvd drive without a disk media inserted?
Answer Use GetDriveType WIN32 Api, and then way to determine if the device is actually a DVD-drive is to use DeviceIOControl such as follows:
C++
#include
<winioctl.h>
BOOL DeviceSupportsDVDMedia(TCHAR *szDrive)
{
BOOL bRet = FALSE;
if(NULL != szDrive && DRIVE_CDROM == GetDriveType(szDrive))
{
GET_MEDIA_TYPES media[CHAR_MAX];
TCHAR szVol[MAX_PATH] = {0};
DWORD dwBytesRet =0;
int iSize = CHAR_MAX * sizeof(GET_MEDIA_TYPES);
_stprintf(szVol,_T("\\\\.\\%c:"),szDrive[0]);
HANDLE hDevice = CreateFile(szVol,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,0);
if(INVALID_HANDLE_VALUE != hDevice)
{
if(DeviceIoControl(hDevice,IOCTL_STORAGE_GET_MEDIA_TYPES_EX,NULL,0,media,iSize,&dwBytesRet,FALSE))
{
	bRet = FILE_DEVICE_DVD == media->DeviceType;
}
}
}
return bRet;
}
 
Question(WIN3202) How to create virtual registry?
Answer Look here Registry Virtualization[^]
 
Question(WIN3203) A question about FreeLibrary?
Complete Question
HMODULE hModule  = ::LoadLibrary("GameLogicWZQ.dll");
typedef GameObject* (*CreateObjProc)();
CreateObjProc pCreateProc = (CreateObjProc)::GetProcAddress(hModule,"CreateGameObject");
m_pGameObject = pCreateProc();
::FreeLibrary(hModule);
If the pCreateProc() function allocates a buffer size of 1024 (using new), then after calling ::FreeLibrary(hModule), will the buffer be free?
Answer No, it won't. A corresponding function should be exported from the DLL that frees that memory. And this function could be called (the same way the Create function is called).
 
Question(WIN3204) How to disable the 'Alt' key System wide?
Answer You might need a kernel-mode device driver. http://technet.microsoft.com/en-us/sysinternals/bb897578.aspx
 
Question(WIN3205) What is the differences Between CreateWindow() and CreateWindowEx?
Answer That are WinApi calls that can be found on MSDN. The Ex stands for extension and if you have a look at the link you'll see that the Ex version has some more options that weren't available at the time of windows 95/98. There are many more api extensions of methods by the way.
 
Question(WIN3206) How to Get GUID for DosDevice?
Complete Question I'm trying to convert a device name of the form "\Device\HarddiskVolumeXX" to a name of the form "\\?\Volume{GUID}.
Answer

 

To start with, run:

mountvol /?
mountvol /L
You will see available mount points for your system.
See http://technet.microsoft.com/en-us/library/cc772586%28WS.10%29.aspx.

Read this CodeProject article: Inside Mountvol.exe about volume mount points and SDK APIs. See also:
 
Question(WIN3207) How can i get the WM_MINIMIZE message of console window?
Answer Probably it isn't a good idea, have a look at the following discussion "Message handling in a console app".
 
Question(WIN3208) How to get the main thread ID of a process (known by its ID) ?
Answer Much faster, but only WIN32: Get the ThreadId with this function:
C++
/* CAUTION: ONLY WIN32
* get the threadId of the main thread of a target process
*
* params:
*     DWORD pId    processId of the target process
*
* return:
*     Success      threadId
*     Error        NULL
*/
DWORD GetMainThreadId(DWORD pId)
{
LPVOID lpThId;
 
_asm
{
mov eax, fs:[18h]
add eax, 36
mov [lpThId], eax
}
 
HANDLE hProcess = OpenProcess(PROCESS_VM_READ, FALSE, pId);
if(hProcess == NULL)
return NULL;
 
DWORD tId;
if(ReadProcessMemory(hProcess, lpThId, &tId, sizeof(tId), NULL) == FALSE)
{
CloseHandle(hProcess);
return NULL;
}
 
CloseHandle(hProcess);
 
return tId;
}
 
Question(WIN3209) How do we determine the base address of a loaded DLL?
Answer The HMODULE that you get from the GetModuleHandle function is the same as the base address. If you are writing MFC applications... this will be the same address returned from AfxGetResourceHandle. The AfxGetInstanceHandle function is actually returning the base address of the main application image.

If you are using a Microsoft compiler then you also have access to an extern variable __ImageBase which can be used to access the these base addresses. Because it is equal to an HMODULE you can also use this variable for loading resources.
Now that we have the base address we can read the PE image headers and check for a size:
C++
DWORD GetSizeOfImage(HMODULE hModule))
{
DWORD dwSize = 0;
PIMAGE_DOS_HEADER pDOSHeader = (PIMAGE_DOS_HEADER)hModule;
PIMAGE_NT_HEADERS pNTHeader = (PIMAGE_NT_HEADERS)((PBYTE)hModule + pDOSHeader->e_lfanew);
if(IMAGE_NT_SIGNATURE == pNTHeader->Signature)
{
PIMAGE_FILE_HEADER pFileHeader = (PIMAGE_FILE_HEADER)((PBYTE)&pNTHeader->FileHeader);
PIMAGE_OPTIONAL_HEADER pOptionalHeader = (PIMAGE_OPTIONAL_HEADER)((PBYTE)&pNTHeader->OptionalHeader);
if(IMAGE_NT_OPTIONAL_HDR32_MAGIC ==  pNTHeader->OptionalHeader.Magic)
{
dwSize = pNTHeader->OptionalHeader.SizeOfImage;
}
}
return dwSize;
}
 
Question(WIN3210) How to tell the system to load a DLL at a base address that I specify?
Answer

 

Check out the /FIXED (Fixed Base Address) linker option.

I consider fixed base addresses to be an insecure option... I highly recommend that all software engineers support a dynamic base address.

PE images with support for ASLR will have the IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE bit set in the PE image characteristics. These modules are essentially saying 'put me anywhere you want... I don't care' and the kernel pseudo-randomly chooses an address to map the image.

PE images without support for ASLR... the NT kernel will make an attempt to load the image at its preferred address at pNTHeader->OptionalHeader.ImageBase. If the address is already allocated the kernel will make an attempt to map the image at another address and apply its fixups.

 
Question(WIN3211) How can I check if window is hidden by another window?
Answer

 

The GetClipBox Function will return a NULLREGION if the window is completely obscured. Unfortunately this will not work if DWM/Aero is enabled and you will probably need to calculates the intersections.

 
Question(WIN3212) Difference between dynamic linking vs dynamic loading ?
Answer

Dynamic linking: your code is built to use functions in a shared library; your code runs, the OS finds the shared lib and gives you access to the functions you need.

Dynamic loading: your code can discover, load and execute code from shared libraries. but the shared libraries might not even exist at run time. your code explicitly loads the shared library. best example of this is plugins.

 
Question((WIN3213) Is there a way to prevent the user from logging off from their Windows account while my application is running?
Answer

 

Method for XP or earlier is slightly different from Vista/Win7 from my experience.

For XP or earlier, return 0 for WM_QUERYENDSESSION and this should be enough.

For Vista/Win7, I haven't found a way to entirely stop logging off. But temporarily blocking logging off is possible. I would return 1 for WM_QUERYENDSESSION and register a blocking reason during WM_ENDSESSION, by calling ShutdownBlockReasonCreate. Then call ShutdownBlockReasonDestroy when your application is finished running.

You should obey the description mentioned in WM_ENDSESSION Message and WM_QUERYENDSESSION to make sure both user and Windows system are happy.

 
   

GENERAL

 
   
Question(GEN01) Shall I use destructor in a pure virtural class?And when?
Complete Question Recently, I got a question, about pure virtual class. Sometimes I need to design an interface for my job, looks like:
C++
class CInterface
{
virtual ~CInterface()=0{}
virtual void SomeAction()=0;
}
 
class DerivedA:public CInterface
{
DerivedA(){}
~DerivedA(){}
void SomeAction()
{
cout<<"Action from Derived class A ."<<endl;
}
}
But what make me confused is that it works well after I change CInterface,like below:

class CInterface
{
//virtual ~CInterface()=0{}
virtual void SomeAction()=0;
}
So, my question is, shall I use destructor in a pure virtural class?And when?
 
 
Answer Answer#1
You only need a destructor if you need to deallocate pointers (or free resources) that were allocated within the pure virtual class itself.

Answer#2
I think you declared the destructor of CInterface as private(default declaration), so that is why your first code did not worked.In the second since you commented it compiler generated the default destructor for you. But As for as i know you should declare virtual destrucor and in the Interface(Generic Class).The use of this destructor will be explained in this example,
C++
class CInterface
{
public:
virtual ~CInterface() = 0 {};
virtual void SomeAction()=0;
};
class DerivedA:public CInterface
{
public:
DerivedA(){}
~DerivedA(){cout<<"In Deriveda"<<endl;}
void SomeAction()
{
cout<<"Action from Derived class A ."<<endl;
}
};
int main()
{
CInterface* A = new DerivedA;
delete A;
return 0;
}
So if you delete A pointer the CInterface destructor will be called automatically by the compiler. if you wont decalre it as virtual or not declared at all the CInterface destructor will not be called. As for as i know virtual ~CInterface() = 0; and virtual ~CInterface(); are same in a Interface with only one differance. i.e. If you want to make a class pure virtual and that class is not having any functions then you can make the destructor as pure virtual, so that the whole class become virtual.

Answer#3
If your base class doesn't define a virtual destructor and your inherited classes implement a destructor, then you will encounter the problem he described: your derived destructors will not be called if the object you are deleting is not from that exact class (a base class pointer). To make short I would say: always define a virtual destructor in your base abstract classes.
  • If you implement a destructor in a derived type, this destructor will be called in any case.
  • If you don't need a destructor in your inherited classes, this will not hurt.
 
Question(GEN02) I have a varibale of 8 bytes (ULONGLONG). How to extract first 6 bytes from that?
Answer

 

Here this might help

C++
#include <windows.h>
#include <iostream>

using namespace std;
 
union MyUnion
{
ULONGLONG ull;
BYTE b[8];
};
 
int main()
{
ULONGLONG v = 0x0123456789ABCDEF;
MyUnion mu;
mu.ull = v;
for (int i=0; i<6; i++)
{
// assuming you need the least significative bytes
cout << hex << (INT) mu.b[i] << endl;
}
}
 
Question(GEN03) Can you please tell me if there is any particular reason why the following operators (. :: ?: sizeof)can't be oveloaded..
Answer

 

You can read what the inventor of the language, Bjarne Stroustrup, thinks about this right here[^]. No-one can give you a better explanation than him.

 
Question(GEN04) Pop up like windows media player minibar(when minimised)?
Answer

 

What you need is a Deskband.There are 4 types of deskband objects. 3 of them reside inside internet explorer. The last one is on the desktop.Look at the second image in the article Implementing Shell Desk Band and Internet Explorer Bars

 
Question(GEN05) How can a program know if "Microsoft Visual C++ 2010 Redistributable Package (x86)" is installed?
Answer

 

From MSDN blogs: How to detect the presence of Visual C++ 2010 redistributable package.

 
Question(GEN06) How to read a UDF format file?
Answer

 

What You need can be found at : http://msdn.microsoft.com/en-us/library/aa366216(VS.85).aspx all necessary interfaces are there ..

 
Question(GEN07) Simulating DOS 6.12 enviornment on Window 7?
Answer

 

You can use DosBox under Windows XP. It should probably work under Windows 7 too.

 
Question(GEN08) What is the return type of a value that is in degrees minutes seconds format?
Answer

 

I would say the return type should be an Angle (or Bearing, ..). Create a class Angle to use. Internally it can use a floating point member for the decimal value. Then add a string formating member function to get the desired string when needed.


Advantages: Easy to perform calculations, and you can reduce the risk of mixing units, such as degrees and radians. I use the following if it helps you in any way

C++
class angle
{
public:
enum unit
{
rad = 0,
deg = 1
};
angle() : r(0.) {}
explicit angle(double a, unit u = rad) {
if (u == rad) r = a; else r = a*M_PI/180;
}
angle(const angle& fi) : r(fi.r) {}
double radians() const { return r; }
double degrees() const { return r*180/M_PI; }
 
// -pi <= a < pi
void normalize() {
while(r<-M_PI)r+=2*M_PI;while(r>=M_PI)r-=2*M_PI;
}
// 0 <= a < 2pi
void normalize_positive() {
while(r<0.)r+=2*M_PI;while(r>=2*M_PI)r-=2*M_PI;
}
 
angle& operator=  (const angle &fi) { if (&fi != this) r = fi.r; return *this; }
angle& operator+= (const angle &fi) { r += fi.r; return *this; }
angle& operator-= (const angle &fi) { r -= fi.r; return *this; }
bool   operator== (const angle &fi) { return r == fi.r; }
bool   operator>  (const angle &fi) { return r > fi.r; }
bool   operator<  (const angle &fi) { return r < fi.r; }
bool   operator>= (const angle &fi) { return r >= fi.r; }
bool   operator<= (const angle &fi) { return r <= fi.r; }
angle  operator-  () { return angle(-r); }
angle  operator-  (const angle& fi) { return angle(r-fi.r); }
protected:
double r;
};
You can easily add your formating functions to this class, or better yet, create a formating class that does the job on an angle instance
 
Question(GEN09) Copying text to the clipboard?
Complete Question

 

Nowadays, when copying text to the clipboard, is it any better to

SetClipboardData
as CF_UNICODETEXT instead of CF_TEXT ? Will it make a difference for the pasting entity ?

Answer

Answer#1
According to MSDN: The system implicitly converts data between certain clipboard formats: if a window requests data in a format that is not on the clipboard, the system converts an available format to the requested format. The system can convert data as indicated in the following table.

C++
Clipboard Format | Conversion Format | Platform Support 
 
CF_OEMTEXT       | CF_TEXT           | Windows NT/Windows 2000, Windows 95/Windows 98/Windows Me 
CF_OEMTEXT       | CF_UNICODETEXT    | Windows NT/Windows 2000 
CF_TEXT          | CF_OEMTEXT        | Windows NT/Windows 2000, Windows 95/Windows 98/Windows Me 
CF_TEXT          | CF_UNICODETEXT    | Windows NT/Windows 2000 
CF_UNICODETEXT   | CF_OEMTEXT        | Windows NT/Windows 2000 
CF_UNICODETEXT   | CF_TEXT           | Windows NT/Windows 2000 
Let me have a simple try on the windows xp:
C++
SetClipboardData(/*an ansi string*/, CF_TEXT);
// then
IsClipboardFormatAvailable(CF_TEXT); // success
IsClipboardFormatAvailable(CF_UNICODETEXT); // success
GetClipboardData(CF_TEXT); // success and read right string
GetClipboardData(CF_UNICODETEXT); // success and read right string
// unicode string also can test passed
but I test on the windows 98, if you SetClipboardData with CF_TEXT, then you must GetClipboardData with CF_TEXT, and if you SetClipboardData with CF_UNICODETEXT, you must GetClipboardData with CF_UNICODETEXT. when I SetClipboardData with
CF_UNICODETEXT
, the notepad(win98) can't paste text from clipboard. so, if you wanna support the windows 98, you must SetClipboardData with CF_TEXT, else you can use any one of them. I recommend you use unicode.

Answer#2
It is better just because you can use Unicode. If your application allows to enter Unicode at all, CF_TEXT is absolutely unacceptable, use CF_UNICODETEXT. This reduces the problem to this one: do you want to support Unicode at all? It really depends on your application and requirements. An application can really be non-Unicode when it supports only ASCII (not even ANSI beyond the code point of 127). Some applications like that do have some right to exist.As a rule of thumb, though, I think its the best to assume that the time of non-Unicode texts has gone.
 
Question(GEN10) How to restrict an object being allocated on the heap??
Answer

 

One way can be declaring a

C++
private:
operator new(size_t);
in the class. No implementation is needed. Simply an expression like new yourclass dosn't compile since a class new operator is declared but cannot be called, being private. This is similar as declaring copy and assign as private to disable copy and assignment capabilities produced by default.
 
Question(GEN11) What is the GUID for " Text transfer" in BlueTooth?
Answer

 

OBEX is used to send files. For sending simple text, SerialPortServiceClass_UUID.

 
Question(GEN12) How to get all Acitve Windows Com Port?
Answer

 

You can refer this article Serial ports. Enumeration and FIFO control

 
Question(GEN13) My process should not get killed using Taskmgr?
Complete Question

 

I have launch one process in windows start up. I want that process should not get killed using task manager or any such application. How should I go for this? 

Answer

Answer#1
 I believe a common approach is to use a "watchdog" process that monitors the main process and re-starts it if it is terminated. Then of course the main process must monitor the watchdog. Not bullet proof but annoying enough.

Answer#2

  • Windows has Job Kernel Object which can be used to monitor activities of processes, even it can be used to monitor the process which created it.
  • JOB_OBJECT_MSG_EXIT_PROCESS can be used to if the process gets terminated.
  • By handling the above message the terminated process can be restarted by calling CreateProcess() or spawn(). 
Answer#3
If you are operating at the "USER LEVEL" (your process is running under the user account, respect to the OS) then you cannot do that (and it sounds very suspicions doing that).

You application, respect to the user, has exactly the same rights every other application has, and don't include the right to change the OS behavior respect to the computer (that belongs to the user, not to you) or to the user himself (he has the licence to use all the features of the OS he payed for, not you)

Of course you can implement some tricks like making another process to control the first and restart it if dead. But the user can himself stop them both.

If you own the computers (in the same that they belong to a same organization you and your users also belongs) the clean solution is to operate a process running at system level (in practice a service) running under an administrative account (ideally a specific one) distinct from the user one, that has the grant to start process under user impersonation. In other words, you create in your organization a "user" that has the power to control the user's running process.
 
Question(GEN14)

Difference between strcpy_s vs StringCchCopy?

Answer Answer#1
If you really want to use the "safe" ones (they are not really safe, and are slow), I'd go with strcpy_s. It is provided with CRT, whereas
StringCchCopy
depends on Windows version - it is supported only in XP SP2 and above.

Answer#2
Both Versions are "Secure". I personally prefer the "StringCchCopy" versions since they are cleaner and more consistent then the *_S versions.
 
Question(GEN15) Multilevel inheritance with Pure virtual function?
Complete Question Suppose if the class hierarchy as shown below:
A
|
B
|
C

class C is derived from class B which is in-turn derived from class A;
Class A has some pure virtual functions which have been defined by B with respect to its context;
my query is: if in Class C the pure virtual functions are to be redefined to its specific context then How do I do it????
Answer For instance:
C++
#include
<iostream> 
using namespace std; 
 
class A
{
public:
virtual void show()=0;
};
 
class B: public A
{
public:
virtual void show(){cout << "Hey, I'm a B" << endl;}
};
 
class C: public B
{
public:
virtual void show(){cout << "Hey, I'm a C" << endl;}
};
 
int main()
{
A * p = new C();
p->show();
}
outputs
C++
Hey, I'm a C
 
Question(GEN16)

How To Find String Literals?

Answer

Answer#1
Concrete regular exceptions is not something to be known to be in someone's possession. This is something to be build to the required task. No, they won't help you where a serious parser is required. Do I understand you right that you want to parse C++ code? You will need to learn this field. Start here:

Answer#2 The Find and Replace feature in Visual Studio will accept regular expressions: Regular Expressions (Visual Studio)
To search for single and double quoted literal string and replace them with the _T macro:
  1. Backup your project! I take no responsibility for the outcome.
  2. Open Find and Replace menu.
  3. Add the following text into the find box: {:q}
  4. Add the following to the replace box: _T(\1)
  5. Iterate through the matches and selectively replace your strings. I recommend avoiding the Replace All button as undo will probably not be available.
Note that #include statements and various other unwanted positive matches will occur with this method. You should make a backup of your project just in case something goes wrong.
 
Question(GEN17) Why c++ doesn"t have virtual constructor?
Answer

 

The "virtual" mechanism depends on the VTable, which will be setup by the constructor. So, the constructor itself cannot be virtual (not with C++), even though you could try something like this. The link that I've provided to you is among one of the best C++ FAQs on the internet. You may as well refer to it to read about Virtual destructors and other basic C++ stuff.

When you construct your object, you always know the type of object you want to create at that time (you always call a specific constructor, not the one from the base class). So, it doesn't make sense to have a virtual constructor. Virtual destructors make more sense: when you destroy your object, you often manipulate objects as a pointer to their base class (typical scenario where polymorphism is used). In that case, you want to call the correct version of your destructor.

 
Question(GEN18) What is an interrupt number? What is AX register?
Answer

 

Interrupt numbers are used by the hardware to signal the operating system when some external event occurs. The AX register is merely a general purpose register used by the CPU. Neither of them are specific to a mouse program (whatever that may be). Take a look here for some information on how processors work.

 
Question(GEN19) How to convert double to BSTR?
Answer Answer#1
You may just represent a double value with a BSTR, for instance
C++
#include <windows.h>
#include <tchar.h>
#include <sstream>
using namespace std;
 
int main()
{
wostringstream wos;
double d = 0.57;
wos << d;
BSTR bstr = SysAllocString(wos.str().c_str());
// enjoy with bstr
// ...
SysFreeString(bstr);
}

Answer#2
Why not use VarBstrFromR8 Windows API?
There are many other Data Type Conversion Functions provided with Windows too.
 
Question(GEN20) Where can I get WinUSB.sys and WinUSB.dll?
Answer It comes as a co-installer along with WDK. Read winusb_howto.docx on this page - How to Use WinUSB to Communicate with a USB Device
   
Question(GEN21) Please provide cross-casting practical code?
Answer I'll give a generic example.Imagine we have four class : ANIMAL, FLYER, DOG, CROWN.
C++
class Animal {
public:
virtual ~Animal() {};
void talk (string sound) {
cout << " Grrrr " << (char *)&sound <<  endl;
}
};
 

class Flyer {
public:
void fly (string destination) {
cout << " Flying to " << (char *)&destination <<  endl;
}
}; 
 
class Dog:public Animal{
};
 

class Crow:public Animal, public Flyer{
};
To save the object of type Dog and Crow we need to do an upcast to the base class animal. when we need to call a fly() method of each Crow we need to know if the animal inherits from Flyer class or not, this is done by a cross-cast :
C++
Flyer* myAnimal = dynamic_cast<Flyer*>(pAnimal);
 
if(!myAnimal)
cout<<" my animal can't fly :( ..."<< endl;
else
cout<<" my animal can flye :) ..."<< endl;
   
Question(GEN22) Why "var" prints "Whats up" instead of "newval"?
Complete Question

 

In Release mode with VS2008, Why "var" prints "Whats up" instead of "newval" It crashes in debug mode. I guess the reason might be the auto-memory allocation is "read-only". If I use char *var = new char[15] then it works fine.

C++
#include <stdio.h>
#include <conio.h>
#include <string>
 
int main()
{
char *var = "\nWhats Up";
strcpy(var, "newval");
printf(var);
getch();
return 0;
}
Answer When you create var in this way it is pointing to a constant string so your strcpy() command is not allowed. What you should code is:
C++
char *var = "\nWhats Up";
var = "newval";
// or
char var[] = "\nWhats Up";
strcpy(var, "newval");
although in the second case you could easily overwrite the buffer if you are not careful.
   

FUNNY

 
   
Question(FUN01) Kundali match making algorithm?
Complete Question

Astrology is a complete science, learning it takes years. There is no shortcut to learn it by google.
You need to go step by step to learn the fundamentals. I dont think you will get an algorith online just like that.


It is something that only astrology professor can tell you. Please contact them

Answer Try using a search engine.
 
Question(FUN02) Solution for water pot problem?
Complete Question

 

There are 5 pots having different amount of water and total amount of water in all the pots is 10 liters.
now we want to have 2 liters of water in each pot but in minimum no of transactions. in starting we can have an array showing the initial content of water in each of the pot or any other structure can also be used.
So please suggest me any algorithm or a way so that i can find an algorithm to solve above problem.

Answer Fill up the pots with water and wait for enough time to pass so there is only 2 liters of water left in the pots.
We don't do your homework
 
Question(FUN03) How UnRAR a rar file with password ?
Answer If you want have a look at source code of a program able to deal with RAR files than check out 7-Zip sources. On the other hand if you wish to hack a password-protected RAR file, I doubt you are going to get help here.
   

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_»
  • వేంకటనారాయణ(venkatmakam)
  • Ou Wei

   

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

  • 22 June 2012: Posted on CodeProject.
  • 21 June 2012: 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)


Written By
Software Developer (Senior)
India India
He used to have biography here Smile | :) , but now he will hire someone (for free offcourse Big Grin | :-D ), Who writes his biography on his behalf Smile | :)

He is Great Fan of Mr. Johan Rosengren (his idol),Lim Bio Liong, Nishant S and DavidCrow and Believes that, he will EXCEL in his life by following there steps!!!

He started with Visual C++ then moved to C# then he become language agnostic, you give him task,tell him the language or platform, he we start immediately, if he knows the language otherwise he quickly learn it and start contributing productively

Last but not the least, For good 8 years he was Visual CPP MSMVP!

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA14-Jul-12 20:11
professionalȘtefan-Mihai MOGA14-Jul-12 20:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.