views:

347

answers:

1

I have a button on a form to which I wish to assign a hot-key:

namespace WebBrowser
{
   public partial class MainForm : Form
   {
      public MainForm()
      {
         InitializeComponent();
      }
      int GetPixel(int x, int y)
      {
         Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format32bppPArgb);
         Graphics grp = Graphics.FromImage(bmp);
         grp.CopyFromScreen(new Point(x,y), Point.Empty, new Size(1,1));
         grp.Save();
         return bmp.GetPixel(0, 0).ToArgb();
      }

      //
      // THIS! How can I make a hot-key trigger this button?
      //
      void Button1Click(object sender, EventArgs e)
      {
         int x = Cursor.Position.X;
         int y = Cursor.Position.Y;
         int pixel = GetPixel(x,y);
         textBox1.Text = pixel.ToString();
      }
      void MainFormLoad(object sender, EventArgs e)
      {
         webBrowser1.Navigate("http://google.com");
      }
   }
}
+1  A: 

Assuming this is a WinForms project with a WebBrowser control : the WebBrowser will "eat the keystrokes" anytime it has focus, even if Form KeyPreview is set to 'true.

Try using the WebBrowser PreviewKeyDown event to call the button click :

    private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        // possibly filter here for certain keystrokes ?
        // using e.KeyCode, e.KeyData or whatever
        button1.PerformClick();
    }

If WinForms project, please add WinForms to your tags.

BillW