Archive for June, 2008

How to add ampersand(&) symbol to dialog control captions?

2


For dialog controls we can assign keyboard accelerators. If you give the button text as “&Add”, then really it will become Add” because the ampersand character is used to mark the keyboard accelerator for that control. But what to do if you want the button text to be “Add & Refresh“?


Just use && if you want ampersand as part of caption instead of Keyboard accelerator marker. For instance see the screenshot.


Targeted Audience – Beginners.

How to make dialogs for languages which reads from right to left?

0


Ever thought of designing user interface for a middle east customer in his native language? There are languages which are written from right to left, For instance – Hebrew or Arabic. Obviously the dialogs and controls also should be from right to left, i.e. flipped horizontally. So how can we design such a dialog? With the help of a mirror? or any other cool trick? ;)


As usual, Yes there is! The Visual studio resource editor will take care of it. All you want to do is -

1) Design your dialog as usual. For instance the following dialog.

2) Now take Menu, Layout > Flip. And you’re dialog will be as follows.


Yes! i can read your mind. “The strings are not reversed”. That you can take care while entering the strings. Just enter is as reverse. All visual studio can do is to reverse the layout which itself saves lot of time. isn’t it? ;)


Targeted Audience – Beginners.

How to get the preprocessed C / C++ source files?

6


Everybody knows that before the real compilation, the source file will undergo the stage called preprocessing. All the compiler preprocessors such as #include, #define etc will be processed in this stage and that intermediate preprocessed file, which is the real source – will be fed to compiler for compiling. Its a bit difficult to troubleshoot problems with preprocessor( especially macro expansions ) because, the processed intermediate file is not available. But is to possible to get it?


Ofcourse. You can use the compiler option /P. Take the project settings, In the C/C++ tab add the /P to compiler options. See the screenshot below.

Now if you take your source folder, you can see files with extension *.i
So if you’ve some trouble in macro expansion, just generate the intermediate file and check.


Open the generated intermediate file and see the contents. I’m sure you can’t believe your eyes. ;)


Targeted Audience – Beginners.

How to get the File/Directory change notifications?

1


Usually projects have several settings stored in configuration files and in some special cases, the configuration can change at runtime and the changes should reflect instantaneously. How it can be done? Well, it can be done with the help of a timer and reload the configuration every 5 seconds. Or is there another smarter api? ;)


Yep! you can use – ReadDirectoryChangesW(). It can be called synchronously as well as asynchronously. If its called in synchronous the calling thread will be in blocking state and return only if any file change is detected. See the code snippet for calling it synchronously.

// Directory to watch.
CString csDirectory = _T("C:\\Config");
HANDLE hDirectory = CreateFile( csDirectory,
                              FILE_LIST_DIRECTORY,
                              FILE_SHARE_READ|FILE_SHARE_DELETE,
                              NULL,
                              OPEN_EXISTING,
                              FILE_FLAG_BACKUP_SEMANTICS,
                              NULL );

// Buffer to get the notification information.
const int MAX_BUFFER = 1024;
BYTE Buffer[MAX_BUFFER];
DWORD dwBytesReturned = 0;
ReadDirectoryChangesW( hDirectory,
                     Buffer,
                     MAX_BUFFER,
                     TRUE,
                     FILE_NOTIFY_CHANGE_LAST_WRITE,
                     &dwBytesReturned,
                     0,
                     0 );

// Cast the buffer as Notification Struct.
FILE_NOTIFY_INFORMATION* pNotifyInfo =
    (FILE_NOTIFY_INFORMATION*)( Buffer );

// Changed file.
CString csFileName = pNotifyInfo->FileName;

You can give watch filters via dwNotifyFilter parameter. So that you can watch for specific events such as filename change, new file creation, file size change etc.

The interesting part is – unlike other api’s, ReadDirectoryChangesW() have unicode version only. So don’t forget to add UNICODE and _UNICODE to your project settings. At first if you try to compile it, most probably you’ll hit the following error.

error C2065: 'ReadDirectoryChangesW' : undeclared identifier

For fixing this add _WIN32_WINNT=0×0400 to the preprocessor settings in C/C++ tab of project settings. I hope you understand – why. ;)


Targeted Audience – Intermediate.

How to shutdown or restart a remote machine?

6


You can restart the machine on your table by simply pressing the restart button. But what about a remote machine? For instance, in cable-tv broadband networks, windows machines can be deployed as industrial pc’s which are located several kilometers away from the central server. So its not possible to reach the hardware and restart the pc if needed. So how can you shutdown or restart a remote pc?


You can use the function – InitiateSystemShutdown(). It will initiate the shutdown or restart process in the specified remote machine. See the following code snippet.

// Restart remote machine - RemotePC01
InitiateSystemShutdown( _T("RemotePC01"), // Machine Name.
                        _T("You are going to be restarted"),
                        5000, // timeout
                        TRUE, // Forcefully close applications.
                        TRUE ); // Restart the PC


If you need to abort the shutdown process, you can call AbortSystemShutdown().


Targeted Audience – Beginners.

How to enable/disable all breakpoints in single keystroke?

5


During heavy debugging, we usually have dozens of breakpoints dropped in various locations of source. Some of these breakpoints can also be in the application startup route. While stopping and starting programs during debugging, these breakpoints are really irritating, because they stop always. I’ve to press F5 a couple to times to start the application and run it. If there’s some shortcuts to enable and disable all break points at one single keystroke, it will be nice. isn’t it? But how?


You can use the VisualStudio’s powerful object model to do so. See the macro code for enabling and disabling the breakpoints. In later steps, i’ll explain how to map it to keystroke. The macro code is as follows,

' Macro to Enable all Breakpoints.
Sub EnableBreakPoints()
    Dim myBreakpoint
    For Each myBreakpoint in Debugger.Breakpoints
        ' Enable the break points.
        myBreakpoint.Enabled=True
    Next
End Sub

' Macro to Disable all Breakpoints.
Sub DisableBreakPoints()
    Dim myBreakpoint
    For Each myBreakpoint in Debugger.Breakpoints
        ' Disable the break points.
        myBreakpoint.Enabled=False
    Next
End Sub

How to map the macros to Keystroke
1) Take Tools > Macro.
2) Now you’ll see your macro window and i assume no macros are defined in your macro file. For getting the macro editor, enter some dummy macro name and click “edit” button.

3) Now Macro editor will be opened and copy-paste the Enable/Disable macro code in your macro editor and save it.
4) Now take Tools > Macro again and VisualStudio will ask, whether to reload the macros. Press Yes.
5) Now you’ll see the macro dialog, and click “Options” and “Keystrokes“.

6) Now select the macro and press a key combination, then click “Assign”.

7) The greatest difficult that you’ll face is to find a free slot of key combination. Almost all are reserved by visual studio itself. :) After some R&D I’ve found two working key combinationAlt+z and Alt+x. Map your enable/disable macros to those shortcuts.

8 ) Now take visual studio and press the key combination to disable the breakpoints. Note that the breakpoints will not be visually disabled but if you take breakpoint window by Ctrl+B you can see all are disabled. This happens because we’ve modified the internal structure of VisualStudio, but GUI is not refreshed.


The only drawback is the breakpoints will not be visually disabled on keystroke. I’m searching for some solution and hope i’ll be back soon. Till then enjoy this one. ;)


Targeted Audience – Intermediate.

How to find the GdiObject type from handle.

0


Gdi Objects are represented by handles. Basically all handles are just an integer inside. For instance, if you’re writing a function with accepts HFONT as parameter, its quite possible to pass a typecasted handle of other Gdi object. So how can you determine the real Gdi object type from the handle?


You can use the function – GetObjectType(). See the following code snippet.

// Get the Black Brush.
HGDIOBJ hGdiObj = GetStockObject( BLACK_BRUSH );

// Check the object type with handle.
if( OBJ_BRUSH == GetObjectType( hGdiObj ))
{
    // Yes! The handle points to Gdi Brush.
}

So now add better error checking in your gdi routines. ;)


The values that GetObjectType() returns are,

  • OBJ_BITMAP – Bitmap
  • OBJ_BRUSH – Brush
  • OBJ_COLORSPACE – Color space
  • OBJ_DC Device – Context
  • OBJ_ENHMETADC – Enhanced metafile DC
  • OBJ_ENHMETAFILE – Enhanced metafile
  • OBJ_EXTPEN – Extended pen
  • OBJ_FONT – Font
  • OBJ_MEMDC – Memory DC
  • OBJ_METAFILE – Metafile
  • OBJ_METADC – Metafile DC
  • OBJ_PAL – Palette
  • OBJ_PEN – Pen
  • OBJ_REGION – Region


Targeted Audience – Beginners.

How to manipulate bits easily?

0


We usually use & operator for checking bits in an integer value. Is there any easy method to manipulate bits? You can use STL bitset container. But it’s not a container like vector or list. So it does not have iterators.


The bitset should be initialized with the number of bits. See the sample code block below.

// Initialize bitset with number of bits required.
// Here its for holding an integer.
bitset<sizeof(int) * 8> IntegerBits = 12478;

// I wanna see the value in binary.
cout << "Binary of 12478 is :" << IntegerBits << endl;

// How many bits are present?
cout << "Number of bits:" << IntegerBits.size() << endl;

// Check whether 10th bit is set.
cout << "10th bit is:" << IntegerBits[10] << endl;

// Flip all bits and display.
IntegerBits.flip();
cout << "Flipped Binary of 12478 is :" << IntegerBits << endl;

Now getting and manipulating bits is just like a breeze. nah?


Targeted Audience – Beginners.

How to fill gradients in your dialog like InstallShield?

1


Look at the dialog. What’s the first thing that come to your mind when you see this?

Yes! I can read it – the InstallShield. Its so common to our eyes, since almost all application setups comes via InstallShield. People identify installshield with its nice blue gradient in its background window. So how can we generate such nice gradient background like installShield does?


You can use the function – GradientFill(). See the code snippet to generate the InstallShield effect. Its self explanatory.

// Get the Device context.
CPaintDC dc( this );

// Get the client co-ordinates.
CRect rect;
GetClientRect( &rect );

// Two gradient points.
TRIVERTEX vert[2] = { 0 };

// Set the first vertex point at 0,0 and with blue color.
// Since the array is initialize with 0, all other
// members in struct are 0.
vert[ 0 ] .Blue   = 0xff00;

// Initialize second vertex at endcorner of
// window with black color.
vert[ 1 ] .x      = rect.Width();
vert[ 1 ] .y      = rect.Height();

// Gradient rectangle.
GRADIENT_RECT GradientRect = { 0 };
GradientRect.UpperLeft = 0;
GradientRect.LowerRight = 1;

// Now fill the gradient.
GradientFill( dc.GetSafeHdc(),
              vert, // Gradient vertices.
              2,    // No. of vertices.
              &GradientRect, // Gradient array.
              1,    // No. of items in Gradient Array.
              GRADIENT_FILL_RECT_V ); // Vertical Fill.


Don’t forget to add Msimg32.lib to your project settings.


Targeted Audience – Intermediate.

How to catch exceptions from constructor initializer list?

4


C++ provides constructor initializer list to initialize member variables of type reference, const etc. In the constructor initialize list, we can initialize ordinary objects too. See sample below.

MyClass::MyClass( int var1, int var2 )
    : m_var1( var1 ),
      m_obj2( var1 ) // If this one throws an exception,
                     // it can't be caught.
{
    try
    {
       // Constructor body.
    }
    catch( ... )
    { }
}

But did you noticed that, these constructor initialize list is outside the function body, and if an exception is thrown from any of the member variable’s constructor, how it can be caught?


There is a special kind of try-catch usage to catch exceptions from constructor initialize list. See the code snippet below.

MyClass::MyClass( int var1, int var2 )
    try : m_var1( var1 ),
          m_obj2( var1 )    // Now I can catch the exception.
{
    // Constructor body.
}
catch( ... )
{ }

Now you can catch exceptions from constructor member initializer list also.


You cannot compile this in Visual C++ 6.0, since its does not strictly confirms C++ standards. You can compile this on Visual Studio 7.0 onwards.


Targeted Audience – Intermediate.

Go to Top