65.9K
CodeProject is changing. Read more.
Home

Help Button Emulation

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (8 votes)

Mar 25, 2009

CPOL

1 min read

viewsIcon

50905

downloadIcon

1217

Help button emulation using Win32 API function

Introduction

Some time ago, while I was writing an application, I required a Help Button. The functionality of this button is widely known: by clicking on this first and then on any control of the client area, you will receive a tooltip including help and information about the element itself.
Adding a Help Button in a C# program is relatively simple. 

For this purpose, there is a property named Form.HelpButton, which when true, makes a small button with a question mark appear in the caption bar to the left of the Close button. At this point, however, a problem arises, the property is ignored if one (or both), of these two properties, Form.MinimizeBox and Form.MaximizeBox are true. In other words, to have a Help Button, we should renounce to Window's minimization and maximization.
So, is there a way to avoid this? The answer is yes, by using help button emulation!

The Code

To resolve this task we will use a function, from the Win32 API called SendMessage. This function, which sends a message to a window, called with some specific parameters is all we need. That said, the first thing to do is to import the DLL which contains SendMessage and declare two constants we need:

[DllImport( "user32.dll", CharSet = CharSet.Auto, SetLastError = false )]
private static extern IntPtr SendMessage
	( IntPtr hWnd, Int32 Msg, IntPtr wParam, IntPtr lParam );

private const int WM_SYSCOMMAND = 0x112;
private const int SC_CONTEXTHELP = 0xf180;

Once this is done, we must use a HelpProvider object whose job is to intercept the help request and show the appropriate tooltip:

private System.Windows.Forms.HelpProvider helpProvider1;

// Set the Help string associated with the textBox1.
helpProvider1.SetHelpString( textBox1, "Sample help string." );
helpProvider1.SetShowHelp( textBox1, true );

Finally, we deal with the real help button's emulation. In the Click event, we must call the SendMessage function with appropriate parameters:

private void btnHelp_Click( object sender, EventArgs e )
{
 // Setting Capture to false, will make the control 
 // not receive all mouse events: the window procedure doesn't receive
 // messages when the mouse is outside the window's client area.
 btnHelp.Capture = false;
 // Simulate the help button press with SendMessage function.
 SendMessage( this.Handle, WM_SYSCOMMAND, ( IntPtr )SC_CONTEXTHELP, IntPtr.Zero );
}

That's all! In these simple steps, we have a window containing both a Help Button and minimize and maximize.

History

  • 25th March, 2009: Initial post