按下键时执行操作

时间:2019-09-06 13:11:20

标签: c# visual-studio

我正在我的项目上,我需要添加仅在按下CTRL的同时执行的操作

这是我的代码:

   private void Izrada_kartice_KeyDown(object sender,KeyEventArgs e)
    {

        if(e.Control)
        {
            promijeni_veličinu_naslov = true;

            this.BackColor = Color.Red;
        }

    }

    private void Izrada_kartice_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Control)
        {
            promijeni_veličinu_naslov = false;

            this.BackColor = Color.Green;
        }
    }

现在,当我运行此代码并按CTRL时,一切正常,但是当我释放CTRL时  什么都没发生。

我曾经尝试过:

     private void Izrada_kartice_KeyDown(object sender,KeyEventArgs e)
{

    if(e.KeyCode == Keys.A)
    {
        promijeni_veličinu_naslov = true;

        this.BackColor = Color.Red;
    }

}

private void Izrada_kartice_KeyUp(object sender, KeyEventArgs e)
{
        if(e.KeyCode == Keys.A)
    {
        promijeni_veličinu_naslov = false;

        this.BackColor = Color.Green;
    }
}

这很好用,但我需要使用CTRL

2 个答案:

答案 0 :(得分:1)

释放Ctrl时,将触发KeyUp事件,但是e.Control布尔值未设置为True,因为不再按住Ctrl。

简而言之:不要通过检查e.Control来检测Ctrl的释放,而应检查e.KeyCode;将会是Keys.ControlKey

if(e.KeyCode == Keys.ControlKey)
{
    ...
}

答案 1 :(得分:0)

在第二个代码上,将Keys.A替换为Keys.ControlKey,如下所示:

private void Izrada_kartice_KeyDown(object 
sender,KeyEventArgs e)
{

if(e.KeyCode == Keys.ControlKey)
{
    promijeni_veličinu_naslov = true;

    this.BackColor = Color.Red;
}

}

private void Izrada_kartice_KeyUp(object sender, 
KeyEventArgs e)
{
    if(e.KeyCode == Keys.ControlKey)
{
    promijeni_veličinu_naslov = false;

    this.BackColor = Color.Green;
}
}