views:

18

answers:

1

Hi all. I'm trying to get a hotkey control working in C# based on both the Control class and the msctls_hotkey32 win32 class. What I have works, though it's not perfect:

    class Hotkey : TextBox
    {
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parms = base.CreateParams;
                parms.ClassName = "msctls_hotkey32";
                return parms;
            }
        }
        // (some other p/invoke stuff for HKM_SETHOTKEY, etc.)
    }

The advantages are that it's simple and it works. The disadvantage is that it inherits a bunch of functionality from TextBox that doesn't apply to this control. So my question is - is there a better way to do this without reinventing the wheel?

Thanks.

+1  A: 

You could always inherit directly from System.Windows.Forms.Control. And then of course add the specific methods and properties that you want to support. You will need to set the control styles appropriately for this to work, here is a quick example.

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  class HotKey : Control  
  {
    public HotKey()
    {
      SetStyle(ControlStyles.UserPaint, false);
    }

    protected override CreateParams CreateParams
    {
      get
      {
        CreateParams cp = base.CreateParams;
        cp.ClassName = "msctls_hotkey32";

        return cp;
      }
    }
  }
}
Chris Taylor
Previously when I tried deriving from Control, it didn't work - it seemed that the control was "read-only", was grey and though the text cursor was blinking in it it didn't accept any input. Adding that SetStyle call fixed that, though. What does it do, exactly?
Reinderien
Basically it tells the control that the painting will not be done by the control code, by default the Control class assumes that the painting of the control will be done by the control it self, but in this case the painting needs to be done by the native control so setting the UserPaint flag to false tells the Control not to raise the Paint event.
Chris Taylor
Awesome, well it works perfectly, thanks.
Reinderien