【问题标题】:How to show a message when Alt is pressed in C# using KeyPress event?如何在 C# 中使用 KeyPress 事件按下 Alt 时显示消息?
【发布时间】:2021-01-24 18:10:24
【问题描述】:

我想在 Windows 窗体应用程序和 C# 中使用 KeyPress 事件按下 Alt 时显示一条消息。以下代码仅适用于 Shift 和 Control,但不适用于 Alt。它没有给我一个错误,但是当我执行程序时它不起作用。

 public static System.Windows.Forms.Keys ModifierKeys
        {
            get;
        }
 private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {

            if((Control.ModifierKeys & Keys.Alt) == Keys.Alt)
            
            {
                ((Control)sender).Hide(); 
                MessageBox.Show("pppppppppppppppppppppp");
            }

        }

【问题讨论】:

    标签: c# winforms events


    【解决方案1】:

    使用KeyDown,因为它内置了修饰符和特殊键,Alt 键特别是非字符键。

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Alt)
        {
            MessageBox.Show("Alt key was pressed down");
        }
    }
    

    【讨论】:

      【解决方案2】:

      按键事件:

      using System;
      using System.Windows.Forms;
      
      namespace WindowsFormsApplication1
      {
      public partial class Form1 : Form
      {
          public Form1()
          {
              InitializeComponent();
          }
          private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
          {
              if (e.Modifiers == Keys.Alt)
              {
                  MessageBox.Show("Alt key pressed");
              }
          }
      }
      }
      

      【讨论】:

      • KeyPressEventArgs 没有 Modifiers 属性。
      • 链接到KeyDown 事件,而您的答案是KeyPress 事件,事件参数不同,您是否实际测试过您的答案?
      • 这不是很好,它在 (char)Keys.Alt.``` 下给了我错误 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.Modifiers == Keys .Alt) { MessageBox.Show("Alt 键被按下"); } }```
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多