How can I make a hotkey trigger a Windows Forms button?

一曲冷凌霜 提交于 2019-12-24 00:46:32

问题


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:


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

Use the WebBrowser PreviewKeyDown event to call the button click:

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


来源:https://stackoverflow.com/questions/2474586/how-can-i-make-a-hotkey-trigger-a-windows-forms-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!