如何使热键触发Windows窗体按钮?

时间:2010-03-19 02:13:07

标签: c# winforms hotkeys

我在表单上有一个按钮,我希望分配一个热键:

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 个答案:

答案 0 :(得分:1)

假设这是一个带有WebBrowser控件的Windows窗体项目:即使Form KeyPreview设置为'true',WebBrowser也会“点击按键”,即使Form KeyPreview设置为'true'。

使用WebBrowser PreviewKeyDown事件调用按钮单击:

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