代码之家  ›  专栏  ›  技术社区  ›  user366312

选中的列表框mousemove与mousehover事件处理程序

  •  2
  • user366312  · 技术社区  · 15 年前

    我正在使用以下内容 MouseMove 事件处理程序,将文本文件内容显示为checkedListBox上的工具提示,并为每个checkedListBox项标记一个文本文件对象。

    private void checkedListBox1_MouseMove(object sender, MouseEventArgs e)
            {
                int itemIndex = checkedListBox1.IndexFromPoint(new Point(e.X, e.Y));
    
                if (itemIndex >= 0)
                {
                    if (checkedListBox1.Items[itemIndex] != null)
                    {
                        TextFile tf = (TextFile)checkedListBox1.Items[itemIndex];
    
                        string subString = tf.JavaCode.Substring(0, 350);
    
                        toolTip1.ToolTipTitle = tf.FileInfo.FullName;
                        toolTip1.SetToolTip(checkedListBox1, subString + "\n... ... ...");
                    }
                }
            }
    

    问题是,由于选中的列表框上的鼠标频繁移动,我的应用程序速度减慢。

    作为一种选择,我想,我应该使用 MouseHover 事件及其处理程序。但我找不到我的Musepointer当前所在的checkedListBoxItem。这样地:

    private void checkedListBox1_MouseHover(object sender, EventArgs e)
            {
                if (sender != null)
                {
                    CheckedListBox chk = (CheckedListBox)sender;
    
                    int index = chk.SelectedIndex;
    
                    if (chk != null)
                    {
                        TextFile tf = (TextFile)chk.SelectedItem;
    
                        string subString = tf.FileText.Substring(0, 350);
    
                        toolTip1.ToolTipTitle = tf.FileInfo.FullName;
                        toolTip1.SetToolTip(checkedListBox1, subString + "\n... ... ...");
                    }
                }
            }
    

    在这里 int index 正在返回-1和 chk.SelectedItem 正在回归 null .

    这类问题的解决方案是什么?

    2 回复  |  直到 15 年前
        1
  •  5
  •   Ash    15 年前

    在鼠标悬停事件中,您可以使用 Cursor.Position property 并将其转换为客户机位置并传递到indexFromPoint()以确定它是否包含在哪个列表项中。

    如。

     Point ptCursor = Cursor.Position; 
     ptCursor = PointToClient(ptCursor); 
     int itemIndex=checkedTextBox1.IndexFromPoint(ptCursor);
     ...
     ...
    

    这对其他事件也很有用,因为在这些事件参数中没有给定鼠标位置。

        2
  •  1
  •   Wael Dalloul    15 年前

    问题是因为selecteditem<gt;checkeditem,selected意味着有另一个背景,checked意味着在左侧进行check。

    而不是

     int index = chk.SelectedIndex;
    

    您应该使用:

    int itemIndex = checkedListBox1.IndexFromPoint(new Point(e.X, e.Y));
    bool selected = checkedListBox1.GetItemChecked(itemIndex );
    

    然后显示你想要的,如果它被选中…

    推荐文章