拖动时TreeView自动滚动

时间:2011-05-17 17:49:57

标签: c# winforms treeview

Winforms TreeView,我想在用户拖动项目时向上/向下滚动。

2 个答案:

答案 0 :(得分:21)

与上面几乎相同,但没有“顶级”错误,在较大的项目中使用起来会更简单。

将此课程添加到您的项目中:

public static class NativeMethods
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    public static void Scroll(this Control control)
    {
        var pt = control.PointToClient(Cursor.Position);

        if ((pt.Y + 20) > control.Height)
        {
            // scroll down
            SendMessage(control.Handle, 277, (IntPtr) 1, (IntPtr) 0);
        }
        else if (pt.Y < 20)
        {
            // scroll up
            SendMessage(control.Handle, 277, (IntPtr) 0, (IntPtr) 0);
        }
    }
}

然后只需订阅树视图的DragOver事件(或者您想要在拖放时启用滚动的任何其他控件/自定义控件)并调用Scroll()方法。

    private void treeView_DragOver(object sender, DragEventArgs e)
    {
        treeView.Scroll();
    }

答案 1 :(得分:10)

在树视图控件中实现拖放时,需要支持某种类型的自动滚动功能。例如,当您从可见树节点拖动项目,并且目标树节点位于树视图的当前视图之外时,控件应根据鼠标的方向自动向上或向下滚动。

Windows窗体Treeview控件不包含实现此功能的内置功能。但是,自己实现它很容易。

第1步:让您的树视图拖放代码正常工作

确保树视图拖放代码无需自动滚动即可正常工作。有关如何在树视图中实现拖放的详细信息,请参阅此文件夹中的主题。

步骤2:为SendMessage函数添加定义

为了告诉treeview向上或向下滚动,您需要调用Windows API SendMessage()函数。为此,请将以下代码添加到类的顶部:

// Make sure you have the correct using clause to see DllImport:
// using System.Runtime.InteropServices;
 [DllImport("user32.dll")]
    private static extern int SendMessage (IntPtr hWnd, int wMsg, int wParam, 
        int lParam);

第3步:进入DragScroll事件

在DragScroll事件中,确定鼠标光标相对于树视图控件顶部和底部的位置。然后调用SendMessage滚动为apporpriate。

// Implement an "autoscroll" routine for drag
//  and drop. If the drag cursor moves to the bottom
//  or top of the treeview, call the Windows API
//  SendMessage function to scroll up or down automatically.
private void DragScroll (
    object sender,
    DragEventArgs e)
{
    // Set a constant to define the autoscroll region
    const Single scrollRegion = 20;

    // See where the cursor is
    Point pt =  TreeView1.PointToClient(Cursor.Position);

    // See if we need to scroll up or down
    if ((pt.Y + scrollRegion) > TreeView1.Height)
    {
        // Call the API to scroll down
        SendMessage(TreeView1.Handle, (int)277, (int)1, 0);
    }
    else if (pt.Y < (TreeView1.Top + scrollRegion))
    {
        // Call thje API to scroll up
        SendMessage(TreeView1.Handle, (int)277, (int)0, 0);
}

取自here