Ved*_*ran 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后只需订阅树视图的DragOver事件(或者您希望在拖放时启用滚动的任何其他控件/自定义控件)并调用Scroll()方法.
private void treeView_DragOver(object sender, DragEventArgs e)
{
treeView.Scroll();
}
Run Code Online (Sandbox Code Playgroud)
Sha*_*hin 10
在树视图控件中实现拖放时,需要支持某种类型的自动滚动功能.例如,当您从可见树节点拖动项目,并且目标树节点位于树视图的当前视图之外时,控件应根据鼠标的方向自动向上或向下滚动.
Windows窗体Treeview控件不包含实现此功能的内置功能.但是,自己实现这一点相当容易.
第1步:让您的树视图拖放代码正常工作
确保您的树视图拖放代码无需自动滚动即可正常工作.有关如何在树视图中实现拖放的详细信息,请参阅此文件夹中的主题.
第2步:为SendMessage函数添加定义
为了告诉树视图向上或向下滚动,您需要调用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);
Run Code Online (Sandbox Code Playgroud)
第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);
}
Run Code Online (Sandbox Code Playgroud)
取自这里.