我想检测一个WinForms

我想检测一个WinForms

本文介绍了我想检测一个WinForms ListBox控件双击该项目。 [如何处理的空白区域单击?]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我有一些项目里面一个列表框。结果
I要检测一个双击一个项目。结果
目前我使用的方法有一个问题,如果用户在空白处双击当前选择的项目是信号为双点击。

well i have a listbox with some items inside.
i want to detect a double click on an item.
currently the method i am using have a problem that if a user double click on an empty spot the currently selected item is signaled as double clicked.

更​​新:结果
请注意,这个问题并不像它看起来那么容易起初结果
也注意到,Timwi。答案是不正确的,因为使用了[if(ListBox1.SelectedIndex == -1)部分不被执行,如果有选择的项目和我一个空的空间
I点击不知道谁upvoted他,但他的回答是不正确的。结果
I已有的代码编写的结果
这个部分,如果有,可以转换鼠标坐标到列表框项目,然后问题将是固定的。

Update:
Please note that this question is not as easy as it seems at first.
also note that Timwi answer is not correct because the [if (ListBox1.SelectedIndex == -1)] part dont get executed if there is an item selected and i clicked in an empty spacei dont know who upvoted him but his answer is not correct.
i already had this part of code written
if there is a function that can convert mouse coordinates to a listbox item then the problem will be fixed

推荐答案

还有一个另外的事件: MouseDoubleClick ,它提供MouseEventArgs,因此您可以放心点击坐标。然后,你可以调用 GetItemBounds()来得到的矩形,包含选定的项目,并检查是否鼠标坐标此矩形内:

There is an alternative event: MouseDoubleClick, which provides MouseEventArgs, so you can get click coordinates. Then you can call GetItemBounds() to get rectangle, containing selected item and check if mouse coordinates are within this rectangle:

    private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if(listBox1.SelectedIndex != -1)
        {
            var rect = listBox1.GetItemRectangle(listBox1.SelectedIndex);
            if(rect.Contains(e.Location))
            {
                // process item data here
            }
        }
    }

MouseDoubleClick 版本信息:


  • .NET框架 - Spported:4,3.5,3.0,2.0

  • 的.NET Framework客户端配置文件 - 支持:4,3.5 SP1

这篇关于我想检测一个WinForms ListBox控件双击该项目。 [如何处理的空白区域单击?]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 00:40