问题描述
- C#做上位机时自定义了一个控件,控件对↑键做出反应,发现方向键不好使,按键事件进不去,求助大神!
-
控件主要是想做一个显示速度的条,当按↑时格子文本框变色
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace SpeedBar
{
public partial class SpeedBar : UserControl
{
private Int16 SpeedBarflag = 0;
public SpeedBar()
{InitializeComponent(); } private void SpeedBar_KeyDown(object sender, KeyEventArgs e) { Keys key = e.KeyCode; switch (key) { //↑按键 case Keys.Up: SpeedBarflag ++; if(SpeedBarflag >5) SpeedBarflag=5; if (SpeedBarflag >= 1 && SpeedBarflag<6) { switch(SpeedBarflag) { case 1: SpeedBar1.BackColor=System.Drawing.Color.Red; break; case 2: SpeedBar2.BackColor=System.Drawing.Color.Yellow; break; case 3: SpeedBar3.BackColor=System.Drawing.Color.Green; break; case 4: SpeedBar4.BackColor=System.Drawing.Color.Blue; break; case 5: SpeedBar5.BackColor=System.Drawing.Color.Black; break; } } if (SpeedBarflag > -5 && SpeedBarflag< 1) { switch(SpeedBarflag) { case -4: SpeedBarminus5.BackColor=System.Drawing.Color.White; break; case -3: SpeedBarminus4.BackColor=System.Drawing.Color.White; break; case -2: SpeedBarminus3.BackColor=System.Drawing.Color.White; break; case -1: SpeedBarminus2.BackColor=System.Drawing.Color.White; break; case 0: SpeedBarminus1.BackColor=System.Drawing.Color.White; break; } } break; //↓按键 case Keys.Down: SpeedBarflag --; if(SpeedBarflag <-5) SpeedBarflag=-5; if (SpeedBarflag <= -1 && SpeedBarflag>-6) { switch(SpeedBarflag) { case -1: SpeedBarminus1.BackColor=System.Drawing.Color.Red; break; case -2: SpeedBarminus2.BackColor=System.Drawing.Color.Yellow; break; case -3: SpeedBarminus3.BackColor=System.Drawing.Color.Green; break; case -4: SpeedBarminus4.BackColor=System.Drawing.Color.Blue; break; case -5: SpeedBarminus5.BackColor=System.Drawing.Color.Black; break; } } if (SpeedBarflag < 5 && SpeedBarflag> -1) { switch(SpeedBarflag) { case 4: SpeedBar5.BackColor=System.Drawing.Color.White; break; case 3: SpeedBar4.BackColor=System.Drawing.Color.White; break; case 2: SpeedBar3.BackColor=System.Drawing.Color.White; break; case 1: SpeedBar2.BackColor=System.Drawing.Color.White; break; case 0: SpeedBar1.BackColor=System.Drawing.Color.White; break; } } break; } } }
}
一直想不通为啥按键无效,一直找不到焦点一样,Form有一个keypreview好像是管这个的,可自定义控件里没这个选项。。。求助求助,谢了
解决方案
这个原因太简单了,因为你的控件没有获取到焦点,你这样的功能,一般要使用钩子,否则一失去焦点,功能就失灵了,除非你保证焦点总在这个程序的这个控件上
时间: 2025-01-02 19:30:55