3

我有一个列表框,我可以用按钮删除项目,但我也想用键盘上的删除键删除,我在谷歌上找不到方法,所以有人可以帮我

编辑 它的一个winform应用程序

这是删除按钮的代码:

private void Button3Click(object sender, EventArgs e)
{
    var application = this.GetCurrentApplication();

    if (application == null)
    {
        MessageBox.Show("No Application selected");
        return;
    }

    if (MessageBox.Show("You are about to delete application: " + Environment.NewLine + _applicationListBox.SelectedItem + Environment.NewLine + "Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
    {
        MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
    }
    else if (this._applicationListBox.SelectedIndex >= 0)
    {
        int index = _applicationListBox.SelectedIndex;

        _toepassingIniFile.ToePassingen.Remove(application);
        if (index == _toepassingIniFile.ToePassingen.Count)
            --index;
        application = index < 0 ? null : _toepassingIniFile.ToePassingen[index];

        _toepassingIniFile.Save(application);

        _applicationListBox.DataSource = null;
        _applicationListBox.DataSource = _toepassingIniFile.ToePassingen;

        _applicationListBox.SelectedIndex = index;
    }
}

回答感谢琼斯

private void ApplicationListBoxPreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode ==Keys.Delete )
        {
           deletefromlistbox();
        }
        if (e.KeyCode == Keys.Insert)
        {
            Refreshapplication();
        }

    }

刷新应用程序

private void Refreshapplication()
    {
        var newapplication = new NewApplication(_toepassingIniFile);
        if (newapplication.Run())
        {
            _applicationListBox.DataSource = null;
            _applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
            _applicationListBox.SelectedIndex = _toepassingIniFile.ToePassingen.Count - 1;
            _controllercombobox.DataSource = null;
            _controllercombobox.DataSource = _controllerIniFile.Controllers;
        }
    }
4

2 回答 2

8
applicationListBox.PreviewKeyDown +=new PreviewKeyDownEventHandler(applicationListBox_PreviewKeyDown);

然后

void applicationListBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        //delete
    }
}

然后像 msm8bball 所说的那样抽象出该代码,以便按钮单击和 previewkeydown 调用删除方法

于 2013-06-25T14:13:44.657 回答
0

将删除的逻辑抽象到它自己的函数中。让 Button3Click 调用此函数。

然后,添加一个处理删除的新函数,并让它也调用新函数。使用此事件:http: //msdn.microsoft.com/en-us/library/system.windows.forms.control.onpreviewkeydown.aspx

于 2013-06-25T14:08:40.833 回答