C # capturing basic event keyboard forms

How to catch keyboard events of the main WinForm form, where other controls are located. So I want to catch one event of Ctrl + S and it does not matter where the focus is. But without Pinvoke (hooks and such ...) Only .NET controls internal power.

+6
source share
4 answers

Try this code. Use the IMessageFilter interface, you can filter out any ctrl + key.

 public partial class Form1 : Form, IMessageFilter { public Form1() { InitializeComponent(); Application.AddMessageFilter(this); this.FormClosed += new FormClosedEventHandler(this.Form1_FormClosed); } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { Application.RemoveMessageFilter(this); } public bool PreFilterMessage(ref Message m) { //here you can specify which key you need to filter if (m.Msg == 0x0100 && (Keys)m.WParam.ToInt32() == Keys.S && ModifierKeys == Keys.Control) { return true; } else { return false; } } } 

I tested this and worked for me.

+10
source

The form class (System.Windows.Forms) has OnKeyDown , OnKeyPress, and OnKeyUp event methods that you can use to detect Ctrl + S

use KeyEventArgs in these methods to determine which keys were pressed

EDIT

be sure to include Form.KeyPreview = true; so that the form captures events regardless of focus.

+8
source

Access KeyDown on the form and all its controls.

 private void OnFormLoad(object sender, EventArgs e) { this.KeyDown += OnKeyDown; foreach (Control control in this.Controls) { control.KeyDown += OnKeyDown; } } private void OnKeyDown(object sender, KeyEventArgs e) { if (e.Control) { if (e.KeyValue == (int)Keys.S) { Console.WriteLine("ctrl + s"); } } } 
+1
source

You can add a MenuStrip, and then create a menu item called save and give it a short segment of Ctrl + S. Add an event handler for this. This works even if the focus is on another form control. If you do not like to see MenuStrip; you can also set visible = false. I have to admit that this is ugly.

0
source

Source: https://habr.com/ru/post/892777/


All Articles