我想在 winforms 列表框控件中检测项目双击.[如何处理点击空白区域?]

7

本文介绍了我想在 winforms 列表框控件中检测项目双击.[如何处理点击空白区域?]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个列表框,里面有一些项目.
我想检测一个项目的双击.
目前我使用的方法有一个问题,如果用户双击一个空白点,则当前选定的项目被指示为双击.

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)] 部分不会执行我不知道谁支持他,但他的回答不正确.
我已经编写了这部分代码
如果有可以将鼠标坐标转换为列表框项的功能,那么问题将得到解决

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 space i 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 Framework - 支持:4、3.5、3.0、2.0
  • .NET Framework 客户端配置文件 - 受以下版本支持:4、3.5 SP1

这篇关于我想在 winforms 列表框控件中检测项目双击.[如何处理点击空白区域?]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14