Control.DoDragDrop 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
重载
DoDragDrop(Object, DragDropEffects, Bitmap, Point, Boolean) |
开始拖动操作。 |
DoDragDrop(Object, DragDropEffects) |
开始拖放操作。 |
DoDragDrop(Object, DragDropEffects, Bitmap, Point, Boolean)
开始拖动操作。
public:
System::Windows::Forms::DragDropEffects DoDragDrop(System::Object ^ data, System::Windows::Forms::DragDropEffects allowedEffects, System::Drawing::Bitmap ^ dragImage, System::Drawing::Point cursorOffset, bool useDefaultDragImage);
public System.Windows.Forms.DragDropEffects DoDragDrop (object data, System.Windows.Forms.DragDropEffects allowedEffects, System.Drawing.Bitmap? dragImage, System.Drawing.Point cursorOffset, bool useDefaultDragImage);
member this.DoDragDrop : obj * System.Windows.Forms.DragDropEffects * System.Drawing.Bitmap * System.Drawing.Point * bool -> System.Windows.Forms.DragDropEffects
Public Function DoDragDrop (data As Object, allowedEffects As DragDropEffects, dragImage As Bitmap, cursorOffset As Point, useDefaultDragImage As Boolean) As DragDropEffects
参数
- data
- Object
- allowedEffects
- DragDropEffects
- dragImage
- Bitmap
- cursorOffset
- Point
- useDefaultDragImage
- Boolean
返回
DragDropEffects 枚举的值,它表示在拖放操作期间执行的最终效果。
注解
参数 allowedEffects
确定可以执行哪些拖动操作。 如果拖动操作需要与另一个进程中的应用程序互操作,data
则应是基托管类 (String、 Bitmap或 Metafile) 或实现 的ISerializable某个Object类。 data
也可以是任何 Object 实现 的 IDataObject。 dragImage
是将在拖动操作期间显示的位图,并 cursorOffset
指定光标在 内 dragImage
的位置,这是与左上角的偏移量。 指定 true
为 useDefaultDragImage
以使用大小为 96x96 的分层窗口拖动图像;否则为 false
。 请注意,如果图像宽度或高度超过 300 像素,则混合输出的外边缘 dragImage
。
由于 DoDragDrop(Object, DragDropEffects, Bitmap, Point, Boolean) 在计算 alpha 值时始终执行 RGB 乘法步骤,因此应始终传递 , Bitmap 而不进行预乘 alpha 混合。 传递 Bitmap 具有预乘 alpha 混合的 不会产生错误,但此方法将再次将其相乘,使生成的 alpha 值加倍。
适用于
DoDragDrop(Object, DragDropEffects)
开始拖放操作。
public:
System::Windows::Forms::DragDropEffects DoDragDrop(System::Object ^ data, System::Windows::Forms::DragDropEffects allowedEffects);
public System.Windows.Forms.DragDropEffects DoDragDrop (object data, System.Windows.Forms.DragDropEffects allowedEffects);
member this.DoDragDrop : obj * System.Windows.Forms.DragDropEffects -> System.Windows.Forms.DragDropEffects
Public Function DoDragDrop (data As Object, allowedEffects As DragDropEffects) As DragDropEffects
参数
- data
- Object
要拖动的数据。
- allowedEffects
- DragDropEffects
DragDropEffects 值之一。
返回
DragDropEffects 枚举的值,它表示在拖放操作期间执行的最终效果。
示例
下面的代码示例演示了两 ListBox 个控件之间的拖放操作。 该示例在 DoDragDrop 拖动操作启动时调用 方法。 如果在事件发生期间MouseDown鼠标移动超过SystemInformation.DragSize鼠标位置,则拖动操作将启动。 方法 IndexFromPoint 用于确定事件期间要拖动的项的 MouseDown
索引。
该示例还演示如何使用自定义游标进行拖放操作。 本示例要求在应用程序目录中分别存在两个游标文件和 3dwarro.cur
3dwno.cur
,以便自定义拖放游标和不放置游标。 如果选中 , UseCustomCursorsCheck
CheckBox 将使用自定义游标。 自定义游标在事件处理程序中 GiveFeedback 设置。
键盘状态在右侧 ListBox
的事件处理程序中DragOver进行评估,以确定拖动操作将基于 SHIFT、CTRL、ALT 或 CTRL+ALT 键的状态。 在 事件期间DragOver
,ListBox
还会确定放置位置。 如果要删除的数据不是 ,String
则在 DragEventArgs.Effect 中DragDropEffects将 设置为 None
。 最后,删除的状态显示在 中 DropLocationLabel
Label。
要在右侧 ListBox
删除的数据在事件处理程序中 DragDrop 确定, String
值将添加到 中的 ListBox
相应位置。 如果拖动操作移动到窗体边界之外,则会在事件处理程序中 QueryContinueDrag 取消拖放操作。
using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
namespace Snip_DragNDrop
{
public ref class Form1: public System::Windows::Forms::Form
{
private:
System::Windows::Forms::ListBox^ ListDragSource;
System::Windows::Forms::ListBox^ ListDragTarget;
System::Windows::Forms::CheckBox^ UseCustomCursorsCheck;
System::Windows::Forms::Label ^ DropLocationLabel;
Int32 indexOfItemUnderMouseToDrag;
Int32 indexOfItemUnderMouseToDrop;
Rectangle dragBoxFromMouseDown;
Point screenOffset;
System::Windows::Forms::Cursor^ MyNoDropCursor;
System::Windows::Forms::Cursor^ MyNormalCursor;
public:
Form1()
{
this->ListDragSource = gcnew System::Windows::Forms::ListBox;
this->ListDragTarget = gcnew System::Windows::Forms::ListBox;
this->UseCustomCursorsCheck = gcnew System::Windows::Forms::CheckBox;
this->DropLocationLabel = gcnew System::Windows::Forms::Label;
this->SuspendLayout();
// ListDragSource
array<Object^>^temp0 = {"five","six","seven","eight","nine","ten"};
this->ListDragSource->Items->AddRange( temp0 );
this->ListDragSource->Location = System::Drawing::Point( 10, 17 );
this->ListDragSource->Size = System::Drawing::Size( 120, 225 );
this->ListDragSource->MouseDown += gcnew System::Windows::Forms::MouseEventHandler( this, &Form1::ListDragSource_MouseDown );
this->ListDragSource->QueryContinueDrag += gcnew System::Windows::Forms::QueryContinueDragEventHandler( this, &Form1::ListDragSource_QueryContinueDrag );
this->ListDragSource->MouseUp += gcnew System::Windows::Forms::MouseEventHandler( this, &Form1::ListDragSource_MouseUp );
this->ListDragSource->MouseMove += gcnew System::Windows::Forms::MouseEventHandler( this, &Form1::ListDragSource_MouseMove );
this->ListDragSource->GiveFeedback += gcnew System::Windows::Forms::GiveFeedbackEventHandler( this, &Form1::ListDragSource_GiveFeedback );
// ListDragTarget
this->ListDragTarget->AllowDrop = true;
this->ListDragTarget->Location = System::Drawing::Point( 154, 17 );
this->ListDragTarget->Size = System::Drawing::Size( 120, 225 );
this->ListDragTarget->DragOver += gcnew System::Windows::Forms::DragEventHandler( this, &Form1::ListDragTarget_DragOver );
this->ListDragTarget->DragDrop += gcnew System::Windows::Forms::DragEventHandler( this, &Form1::ListDragTarget_DragDrop );
this->ListDragTarget->DragEnter += gcnew System::Windows::Forms::DragEventHandler( this, &Form1::ListDragTarget_DragEnter );
this->ListDragTarget->DragLeave += gcnew System::EventHandler( this, &Form1::ListDragTarget_DragLeave );
// UseCustomCursorsCheck
this->UseCustomCursorsCheck->Location = System::Drawing::Point( 10, 243 );
this->UseCustomCursorsCheck->Size = System::Drawing::Size( 137, 24 );
this->UseCustomCursorsCheck->Text = "Use Custom Cursors";
// DropLocationLabel
this->DropLocationLabel->Location = System::Drawing::Point( 154, 245 );
this->DropLocationLabel->Size = System::Drawing::Size( 137, 24 );
this->DropLocationLabel->Text = "None";
// Form1
this->ClientSize = System::Drawing::Size( 292, 270 );
array<System::Windows::Forms::Control^>^formControls = {this->ListDragSource,this->ListDragTarget,this->UseCustomCursorsCheck,this->DropLocationLabel};
this->Controls->AddRange( formControls );
this->Text = "drag-and-drop Example";
this->ResumeLayout( false );
}
private:
void ListDragSource_MouseDown( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ e )
{
// Get the index of the item the mouse is below.
indexOfItemUnderMouseToDrag = this->ListDragSource->IndexFromPoint( e->X, e->Y );
if ( indexOfItemUnderMouseToDrag != ListBox::NoMatches )
{
// Remember the point where the mouse down occurred. The DragSize indicates
// the size that the mouse can move before a drag event should be started.
System::Drawing::Size dragSize = SystemInformation::DragSize;
// Create a rectangle using the DragSize, with the mouse position being
// at the center of the rectangle.
dragBoxFromMouseDown = Rectangle(Point(e->X - (dragSize.Width / 2),e->Y - (dragSize.Height / 2)),dragSize);
}
else
dragBoxFromMouseDown = Rectangle::Empty;
// Reset the rectangle if the mouse is not over an item in the ListBox.
}
void ListDragSource_MouseUp( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ /*e*/ )
{
// Reset the drag rectangle when the mouse button is raised.
dragBoxFromMouseDown = Rectangle::Empty;
}
void ListDragSource_MouseMove( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ e )
{
if ( (e->Button & ::MouseButtons::Left) == ::MouseButtons::Left )
{
// If the mouse moves outside the rectangle, start the drag.
if ( dragBoxFromMouseDown != Rectangle::Empty && !dragBoxFromMouseDown.Contains( e->X, e->Y ) )
{
// Create custom cursors for the drag-and-drop operation.
try
{
MyNormalCursor = gcnew System::Windows::Forms::Cursor( "3dwarro.cur" );
MyNoDropCursor = gcnew System::Windows::Forms::Cursor( "3dwno.cur" );
}
catch ( Exception^ )
{
// An error occurred while attempting to load the cursors, so use
// the standard cursors.
this->UseCustomCursorsCheck->Checked = false;
}
__finally
{
// The screenOffset is used to account for any desktop bands
// that may be at the top or left side of the screen when
// determining when to cancel the drag drop operation.
screenOffset = SystemInformation::WorkingArea.Location;
// Proceed with the drag-and-drop, passing in the list item.
DragDropEffects dropEffect = this->ListDragSource->DoDragDrop( ListDragSource->Items[ indexOfItemUnderMouseToDrag ], static_cast<DragDropEffects>(DragDropEffects::All | DragDropEffects::Link) );
// If the drag operation was a move then remove the item.
if ( dropEffect == DragDropEffects::Move )
{
ListDragSource->Items->RemoveAt( indexOfItemUnderMouseToDrag );
// Selects the previous item in the list as long as the list has an item.
if ( indexOfItemUnderMouseToDrag > 0 )
ListDragSource->SelectedIndex = indexOfItemUnderMouseToDrag - 1;
else
if ( ListDragSource->Items->Count > 0 )
// Selects the first item.
ListDragSource->SelectedIndex = 0;
}
// Dispose of the cursors since they are no longer needed.
if ( MyNormalCursor != nullptr )
delete MyNormalCursor;
if ( MyNoDropCursor != nullptr )
delete MyNoDropCursor;
}
}
}
}
void ListDragSource_GiveFeedback( Object^ /*sender*/, System::Windows::Forms::GiveFeedbackEventArgs^ e )
{
// Use custom cursors if the check box is checked.
if ( UseCustomCursorsCheck->Checked )
{
// Sets the custom cursor based upon the effect.
e->UseDefaultCursors = false;
if ( (e->Effect & DragDropEffects::Move) == DragDropEffects::Move )
::Cursor::Current = MyNormalCursor;
else
::Cursor::Current = MyNoDropCursor;
}
}
void ListDragTarget_DragOver( Object^ /*sender*/, System::Windows::Forms::DragEventArgs^ e )
{
// Determine whether string data exists in the drop data. If not, then
// the drop effect reflects that the drop cannot occur.
if ( !e->Data->GetDataPresent( System::String::typeid ) )
{
e->Effect = DragDropEffects::None;
DropLocationLabel->Text = "None - no string data.";
return;
}
// Set the effect based upon the KeyState.
if ( (e->KeyState & (8 + 32)) == (8 + 32) && ((e->AllowedEffect & DragDropEffects::Link) == DragDropEffects::Link) )
{
// KeyState 8 + 32 = CTRL + ALT
// Link drag-and-drop effect.
e->Effect = DragDropEffects::Link;
}
else
if ( (e->KeyState & 32) == 32 && ((e->AllowedEffect & DragDropEffects::Link) == DragDropEffects::Link) )
{
// ALT KeyState for link.
e->Effect = DragDropEffects::Link;
}
else
if ( (e->KeyState & 4) == 4 && ((e->AllowedEffect & DragDropEffects::Move) == DragDropEffects::Move) )
{
// SHIFT KeyState for move.
e->Effect = DragDropEffects::Move;
}
else
if ( (e->KeyState & 8) == 8 && ((e->AllowedEffect & DragDropEffects::Copy) == DragDropEffects::Copy) )
{
// CTRL KeyState for copy.
e->Effect = DragDropEffects::Copy;
}
else
if ( (e->AllowedEffect & DragDropEffects::Move) == DragDropEffects::Move )
{
// By default, the drop action should be move, if allowed.
e->Effect = DragDropEffects::Move;
}
else
e->Effect = DragDropEffects::None;
// Get the index of the item the mouse is below.
// The mouse locations are relative to the screen, so they must be
// converted to client coordinates.
indexOfItemUnderMouseToDrop = ListDragTarget->IndexFromPoint( ListDragTarget->PointToClient( Point(e->X,e->Y) ) );
// Updates the label text.
if ( indexOfItemUnderMouseToDrop != ListBox::NoMatches )
{
DropLocationLabel->Text = String::Concat( "Drops before item # ", (indexOfItemUnderMouseToDrop + 1) );
}
else
DropLocationLabel->Text = "Drops at the end.";
}
void ListDragTarget_DragDrop( Object^ /*sender*/, System::Windows::Forms::DragEventArgs^ e )
{
// Ensure that the list item index is contained in the data.
if ( e->Data->GetDataPresent( System::String::typeid ) )
{
Object^ item = dynamic_cast<Object^>(e->Data->GetData( System::String::typeid ));
// Perform drag-and-drop, depending upon the effect.
if ( e->Effect == DragDropEffects::Copy || e->Effect == DragDropEffects::Move )
{
// Insert the item.
if ( indexOfItemUnderMouseToDrop != ListBox::NoMatches )
ListDragTarget->Items->Insert( indexOfItemUnderMouseToDrop, item );
else
ListDragTarget->Items->Add( item );
}
}
// Reset the label text.
DropLocationLabel->Text = "None";
}
void ListDragSource_QueryContinueDrag( Object^ sender, System::Windows::Forms::QueryContinueDragEventArgs^ e )
{
// Cancel the drag if the mouse moves off the form.
ListBox^ lb = dynamic_cast<ListBox^>(sender);
if ( lb != nullptr )
{
Form^ f = lb->FindForm();
// Cancel the drag if the mouse moves off the form. The screenOffset
// takes into account any desktop bands that may be at the top or left
// side of the screen.
if ( ((Control::MousePosition.X - screenOffset.X) < f->DesktopBounds.Left) || ((Control::MousePosition.X - screenOffset.X) > f->DesktopBounds.Right) || ((Control::MousePosition.Y - screenOffset.Y) < f->DesktopBounds.Top) || ((Control::MousePosition.Y - screenOffset.Y) > f->DesktopBounds.Bottom) )
{
e->Action = DragAction::Cancel;
}
}
}
void ListDragTarget_DragEnter( Object^ /*sender*/, System::Windows::Forms::DragEventArgs^ /*e*/ )
{
// Reset the label text.
DropLocationLabel->Text = "None";
}
void ListDragTarget_DragLeave( Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
// Reset the label text.
DropLocationLabel->Text = "None";
}
};
}
/// The main entry point for the application.
[STAThread]
int main()
{
Application::Run( gcnew Snip_DragNDrop::Form1 );
}
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Snip_DragNDrop
{
public class Form1 : Form
{
private ListBox ListDragSource;
private ListBox ListDragTarget;
private CheckBox UseCustomCursorsCheck;
private Label DropLocationLabel;
private int indexOfItemUnderMouseToDrag;
private int indexOfItemUnderMouseToDrop;
private Rectangle dragBoxFromMouseDown;
private Point screenOffset;
private Cursor MyNoDropCursor;
private Cursor MyNormalCursor;
// The main entry point for the application.
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
this.ListDragSource = new ListBox();
this.ListDragTarget = new ListBox();
this.UseCustomCursorsCheck = new CheckBox();
this.DropLocationLabel = new Label();
this.SuspendLayout();
// ListDragSource
this.ListDragSource.Items.AddRange(new object[] {"one", "two", "three", "four",
"five", "six", "seven", "eight",
"nine", "ten"});
this.ListDragSource.Location = new Point(10, 17);
this.ListDragSource.Size = new Size(120, 225);
this.ListDragSource.MouseDown += this.ListDragSource_MouseDown;
this.ListDragSource.QueryContinueDrag += this.ListDragSource_QueryContinueDrag;
this.ListDragSource.MouseUp += this.ListDragSource_MouseUp;
this.ListDragSource.MouseMove += this.ListDragSource_MouseMove;
this.ListDragSource.GiveFeedback += this.ListDragSource_GiveFeedback;
// ListDragTarget
this.ListDragTarget.AllowDrop = true;
this.ListDragTarget.Location = new Point(154, 17);
this.ListDragTarget.Size = new Size(120, 225);
this.ListDragTarget.DragOver += this.ListDragTarget_DragOver;
this.ListDragTarget.DragDrop += this.ListDragTarget_DragDrop;
this.ListDragTarget.DragEnter += this.ListDragTarget_DragEnter;
this.ListDragTarget.DragLeave += this.ListDragTarget_DragLeave;
// UseCustomCursorsCheck
this.UseCustomCursorsCheck.Location = new Point(10, 243);
this.UseCustomCursorsCheck.Size = new Size(137, 24);
this.UseCustomCursorsCheck.Text = "Use Custom Cursors";
// DropLocationLabel
this.DropLocationLabel.Location = new Point(154, 245);
this.DropLocationLabel.Size = new Size(137, 24);
this.DropLocationLabel.Text = "None";
// Form1
this.ClientSize = new Size(292, 270);
this.Controls.AddRange(new Control[] {
this.ListDragSource,
this.ListDragTarget,
this.UseCustomCursorsCheck,
this.DropLocationLabel});
this.Text = "drag-and-drop Example";
this.ResumeLayout(false);
}
private void ListDragSource_MouseDown(object sender, MouseEventArgs e)
{
// Get the index of the item the mouse is below.
indexOfItemUnderMouseToDrag = ListDragSource.IndexFromPoint(e.X, e.Y);
if (indexOfItemUnderMouseToDrag != ListBox.NoMatches)
{
// Remember the point where the mouse down occurred. The DragSize indicates
// the size that the mouse can move before a drag event should be started.
Size dragSize = SystemInformation.DragSize;
// Create a rectangle using the DragSize, with the mouse position being
// at the center of the rectangle.
dragBoxFromMouseDown = new Rectangle(
new Point(e.X - (dragSize.Width / 2),
e.Y - (dragSize.Height / 2)),
dragSize);
}
else
{
// Reset the rectangle if the mouse is not over an item in the ListBox.
dragBoxFromMouseDown = Rectangle.Empty;
}
}
private void ListDragSource_MouseUp(object sender, MouseEventArgs e)
{
// Reset the drag rectangle when the mouse button is raised.
dragBoxFromMouseDown = Rectangle.Empty;
}
private void ListDragSource_MouseMove(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// If the mouse moves outside the rectangle, start the drag.
if (dragBoxFromMouseDown != Rectangle.Empty &&
!dragBoxFromMouseDown.Contains(e.X, e.Y))
{
// Create custom cursors for the drag-and-drop operation.
try
{
MyNormalCursor = new Cursor("3dwarro.cur");
MyNoDropCursor = new Cursor("3dwno.cur");
}
catch
{
// An error occurred while attempting to load the cursors, so use
// standard cursors.
UseCustomCursorsCheck.Checked = false;
}
finally
{
// The screenOffset is used to account for any desktop bands
// that may be at the top or left side of the screen when
// determining when to cancel the drag drop operation.
screenOffset = SystemInformation.WorkingArea.Location;
// Proceed with the drag-and-drop, passing in the list item.
DragDropEffects dropEffect = ListDragSource.DoDragDrop(ListDragSource.Items[indexOfItemUnderMouseToDrag], DragDropEffects.All | DragDropEffects.Link);
// If the drag operation was a move then remove the item.
if (dropEffect == DragDropEffects.Move)
{
ListDragSource.Items.RemoveAt(indexOfItemUnderMouseToDrag);
// Selects the previous item in the list as long as the list has an item.
if (indexOfItemUnderMouseToDrag > 0)
ListDragSource.SelectedIndex = indexOfItemUnderMouseToDrag - 1;
else if (ListDragSource.Items.Count > 0)
// Selects the first item.
ListDragSource.SelectedIndex = 0;
}
// Dispose of the cursors since they are no longer needed.
if (MyNormalCursor != null)
MyNormalCursor.Dispose();
if (MyNoDropCursor != null)
MyNoDropCursor.Dispose();
}
}
}
}
private void ListDragSource_GiveFeedback(object sender, GiveFeedbackEventArgs e)
{
// Use custom cursors if the check box is checked.
if (UseCustomCursorsCheck.Checked)
{
// Sets the custom cursor based upon the effect.
e.UseDefaultCursors = false;
if ((e.Effect & DragDropEffects.Move) == DragDropEffects.Move)
Cursor.Current = MyNormalCursor;
else
Cursor.Current = MyNoDropCursor;
}
}
private void ListDragTarget_DragOver(object sender, DragEventArgs e)
{
// Determine whether string data exists in the drop data. If not, then
// the drop effect reflects that the drop cannot occur.
if (!e.Data.GetDataPresent(typeof(System.String)))
{
e.Effect = DragDropEffects.None;
DropLocationLabel.Text = "None - no string data.";
return;
}
// Set the effect based upon the KeyState.
if ((e.KeyState & (8 + 32)) == (8 + 32) &&
(e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link)
{
// KeyState 8 + 32 = CTRL + ALT
// Link drag-and-drop effect.
e.Effect = DragDropEffects.Link;
}
else if ((e.KeyState & 32) == 32 &&
(e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link)
{
// ALT KeyState for link.
e.Effect = DragDropEffects.Link;
}
else if ((e.KeyState & 4) == 4 &&
(e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
{
// SHIFT KeyState for move.
e.Effect = DragDropEffects.Move;
}
else if ((e.KeyState & 8) == 8 &&
(e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
{
// CTRL KeyState for copy.
e.Effect = DragDropEffects.Copy;
}
else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
{
// By default, the drop action should be move, if allowed.
e.Effect = DragDropEffects.Move;
}
else
{
e.Effect = DragDropEffects.None;
}
// Get the index of the item the mouse is below.
// The mouse locations are relative to the screen, so they must be
// converted to client coordinates.
indexOfItemUnderMouseToDrop =
ListDragTarget.IndexFromPoint(ListDragTarget.PointToClient(new Point(e.X, e.Y)));
// Updates the label text.
if (indexOfItemUnderMouseToDrop != ListBox.NoMatches)
{
DropLocationLabel.Text = "Drops before item #" + (indexOfItemUnderMouseToDrop + 1);
}
else
{
DropLocationLabel.Text = "Drops at the end.";
}
}
private void ListDragTarget_DragDrop(object sender, DragEventArgs e)
{
// Ensure that the list item index is contained in the data.
if (e.Data.GetDataPresent(typeof(System.String)))
{
Object item = e.Data.GetData(typeof(System.String));
// Perform drag-and-drop, depending upon the effect.
if (e.Effect == DragDropEffects.Copy ||
e.Effect == DragDropEffects.Move)
{
// Insert the item.
if (indexOfItemUnderMouseToDrop != ListBox.NoMatches)
ListDragTarget.Items.Insert(indexOfItemUnderMouseToDrop, item);
else
ListDragTarget.Items.Add(item);
}
}
// Reset the label text.
DropLocationLabel.Text = "None";
}
private void ListDragSource_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
{
// Cancel the drag if the mouse moves off the form.
ListBox lb = sender as ListBox;
if (lb != null)
{
Form f = lb.FindForm();
// Cancel the drag if the mouse moves off the form. The screenOffset
// takes into account any desktop bands that may be at the top or left
// side of the screen.
if (((Control.MousePosition.X - screenOffset.X) < f.DesktopBounds.Left) ||
((Control.MousePosition.X - screenOffset.X) > f.DesktopBounds.Right) ||
((Control.MousePosition.Y - screenOffset.Y) < f.DesktopBounds.Top) ||
((Control.MousePosition.Y - screenOffset.Y) > f.DesktopBounds.Bottom))
{
e.Action = DragAction.Cancel;
}
}
}
private void ListDragTarget_DragEnter(object sender, DragEventArgs e)
{
// Reset the label text.
DropLocationLabel.Text = "None";
}
private void ListDragTarget_DragLeave(object sender, EventArgs e)
{
// Reset the label text.
DropLocationLabel.Text = "None";
}
}
}
Imports System.Drawing
Imports System.Windows.Forms
Public NotInheritable Class Form1
Inherits Form
Friend WithEvents ListDragSource As ListBox
Friend WithEvents ListDragTarget As ListBox
Friend WithEvents UseCustomCursorsCheck As CheckBox
Friend WithEvents DropLocationLabel As Label
Private indexOfItemUnderMouseToDrag As Integer
Private indexOfItemUnderMouseToDrop As Integer
Private dragBoxFromMouseDown As Rectangle
Private screenOffset As Point
Private MyNoDropCursor As Cursor
Private MyNormalCursor As Cursor
<STAThread()>
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
Public Sub New()
MyBase.New()
Me.ListDragSource = New ListBox()
Me.ListDragTarget = New ListBox()
Me.UseCustomCursorsCheck = New CheckBox()
Me.DropLocationLabel = New Label()
Me.SuspendLayout()
' ListDragSource
Me.ListDragSource.Items.AddRange(New Object() {"one", "two", "three", "four",
"five", "six", "seven", "eight",
"nine", "ten"})
Me.ListDragSource.Location = New Point(10, 17)
Me.ListDragSource.Size = New Size(120, 225)
' ListDragTarget
Me.ListDragTarget.AllowDrop = True
Me.ListDragTarget.Location = New Point(154, 17)
Me.ListDragTarget.Size = New Size(120, 225)
' UseCustomCursorsCheck
Me.UseCustomCursorsCheck.Location = New Point(10, 243)
Me.UseCustomCursorsCheck.Size = New Size(137, 24)
Me.UseCustomCursorsCheck.Text = "Use Custom Cursors"
' DropLocationLabel
Me.DropLocationLabel.Location = New Point(154, 245)
Me.DropLocationLabel.Size = New Size(137, 24)
Me.DropLocationLabel.Text = "None"
' Form1
Me.ClientSize = New Size(292, 270)
Me.Controls.AddRange(New Control() {Me.ListDragSource,
Me.ListDragTarget,
Me.UseCustomCursorsCheck,
Me.DropLocationLabel})
Me.Text = "drag-and-drop Example"
Me.ResumeLayout(False)
End Sub
Private Sub ListDragSource_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListDragSource.MouseDown
' Get the index of the item the mouse is below.
indexOfItemUnderMouseToDrag = ListDragSource.IndexFromPoint(e.X, e.Y)
If (indexOfItemUnderMouseToDrag <> ListBox.NoMatches) Then
' Remember the point where the mouse down occurred. The DragSize indicates
' the size that the mouse can move before a drag event should be started.
Dim dragSize As Size = SystemInformation.DragSize
' Create a rectangle using the DragSize, with the mouse position being
' at the center of the rectangle.
dragBoxFromMouseDown = New Rectangle(
New Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)),
dragSize)
Else
' Reset the rectangle if the mouse is not over an item in the ListBox.
dragBoxFromMouseDown = Rectangle.Empty
End If
End Sub
Private Sub ListDragSource_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListDragSource.MouseUp
' Reset the drag rectangle when the mouse button is raised.
dragBoxFromMouseDown = Rectangle.Empty
End Sub
Private Sub ListDragSource_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListDragSource.MouseMove
If ((e.Button And MouseButtons.Left) = MouseButtons.Left) Then
' If the mouse moves outside the rectangle, start the drag.
If (Rectangle.op_Inequality(dragBoxFromMouseDown, Rectangle.Empty) And
Not dragBoxFromMouseDown.Contains(e.X, e.Y)) Then
' Creates custom cursors for the drag-and-drop operation.
Try
MyNormalCursor = New Cursor("3dwarro.cur")
MyNoDropCursor = New Cursor("3dwno.cur")
Catch
' An error occurred while attempting to load the cursors so use
' standard cursors.
UseCustomCursorsCheck.Checked = False
Finally
' The screenOffset is used to account for any desktop bands
' that may be at the top or left side of the screen when
' determining when to cancel the drag drop operation.
screenOffset = SystemInformation.WorkingArea.Location
' Proceed with the drag-and-drop, passing in the list item.
Dim dropEffect As DragDropEffects = ListDragSource.DoDragDrop(
ListDragSource.Items(indexOfItemUnderMouseToDrag),
DragDropEffects.All Or DragDropEffects.Link)
' If the drag operation was a move then remove the item.
If (dropEffect = DragDropEffects.Move) Then
ListDragSource.Items.RemoveAt(indexOfItemUnderMouseToDrag)
' Select the previous item in the list as long as the list has an item.
If (indexOfItemUnderMouseToDrag > 0) Then
ListDragSource.SelectedIndex = indexOfItemUnderMouseToDrag - 1
ElseIf (ListDragSource.Items.Count > 0) Then
' Selects the first item.
ListDragSource.SelectedIndex = 0
End If
End If
' Dispose the cursors since they are no longer needed.
If (Not MyNormalCursor Is Nothing) Then _
MyNormalCursor.Dispose()
If (Not MyNoDropCursor Is Nothing) Then _
MyNoDropCursor.Dispose()
End Try
End If
End If
End Sub
Private Sub ListDragSource_GiveFeedback(ByVal sender As Object, ByVal e As GiveFeedbackEventArgs) Handles ListDragSource.GiveFeedback
' Use custom cursors if the check box is checked.
If (UseCustomCursorsCheck.Checked) Then
' Set the custom cursor based upon the effect.
e.UseDefaultCursors = False
If ((e.Effect And DragDropEffects.Move) = DragDropEffects.Move) Then
Cursor.Current = MyNormalCursor
Else
Cursor.Current = MyNoDropCursor
End If
End If
End Sub
Private Sub ListDragTarget_DragOver(ByVal sender As Object, ByVal e As DragEventArgs) Handles ListDragTarget.DragOver
' Determine whether string data exists in the drop data. If not, then
' the drop effect reflects that the drop cannot occur.
If Not (e.Data.GetDataPresent(GetType(System.String))) Then
e.Effect = DragDropEffects.None
DropLocationLabel.Text = "None - no string data."
Return
End If
' Set the effect based upon the KeyState.
If ((e.KeyState And (8 + 32)) = (8 + 32) And
(e.AllowedEffect And DragDropEffects.Link) = DragDropEffects.Link) Then
' KeyState 8 + 32 = CTRL + ALT
' Link drag-and-drop effect.
e.Effect = DragDropEffects.Link
ElseIf ((e.KeyState And 32) = 32 And
(e.AllowedEffect And DragDropEffects.Link) = DragDropEffects.Link) Then
' ALT KeyState for link.
e.Effect = DragDropEffects.Link
ElseIf ((e.KeyState And 4) = 4 And
(e.AllowedEffect And DragDropEffects.Move) = DragDropEffects.Move) Then
' SHIFT KeyState for move.
e.Effect = DragDropEffects.Move
ElseIf ((e.KeyState And 8) = 8 And
(e.AllowedEffect And DragDropEffects.Copy) = DragDropEffects.Copy) Then
' CTRL KeyState for copy.
e.Effect = DragDropEffects.Copy
ElseIf ((e.AllowedEffect And DragDropEffects.Move) = DragDropEffects.Move) Then
' By default, the drop action should be move, if allowed.
e.Effect = DragDropEffects.Move
Else
e.Effect = DragDropEffects.None
End If
' Gets the index of the item the mouse is below.
' The mouse locations are relative to the screen, so they must be
' converted to client coordinates.
indexOfItemUnderMouseToDrop =
ListDragTarget.IndexFromPoint(ListDragTarget.PointToClient(New Point(e.X, e.Y)))
' Updates the label text.
If (indexOfItemUnderMouseToDrop <> ListBox.NoMatches) Then
DropLocationLabel.Text = "Drops before item #" & (indexOfItemUnderMouseToDrop + 1)
Else
DropLocationLabel.Text = "Drops at the end."
End If
End Sub
Private Sub ListDragTarget_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles ListDragTarget.DragDrop
' Ensures that the list item index is contained in the data.
If (e.Data.GetDataPresent(GetType(System.String))) Then
Dim item As Object = CType(e.Data.GetData(GetType(System.String)), System.Object)
' Perform drag-and-drop, depending upon the effect.
If (e.Effect = DragDropEffects.Copy Or
e.Effect = DragDropEffects.Move) Then
' Insert the item.
If (indexOfItemUnderMouseToDrop <> ListBox.NoMatches) Then
ListDragTarget.Items.Insert(indexOfItemUnderMouseToDrop, item)
Else
ListDragTarget.Items.Add(item)
End If
End If
' Reset the label text.
DropLocationLabel.Text = "None"
End If
End Sub
Private Sub ListDragSource_QueryContinueDrag(ByVal sender As Object, ByVal e As QueryContinueDragEventArgs) Handles ListDragSource.QueryContinueDrag
' Cancel the drag if the mouse moves off the form.
Dim lb As ListBox = CType(sender, ListBox)
If (lb IsNot Nothing) Then
Dim f As Form = lb.FindForm()
' Cancel the drag if the mouse moves off the form. The screenOffset
' takes into account any desktop bands that may be at the top or left
' side of the screen.
If (((Control.MousePosition.X - screenOffset.X) < f.DesktopBounds.Left) Or
((Control.MousePosition.X - screenOffset.X) > f.DesktopBounds.Right) Or
((Control.MousePosition.Y - screenOffset.Y) < f.DesktopBounds.Top) Or
((Control.MousePosition.Y - screenOffset.Y) > f.DesktopBounds.Bottom)) Then
e.Action = DragAction.Cancel
End If
End If
End Sub
Private Sub ListDragTarget_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) Handles ListDragTarget.DragEnter
' Reset the label text.
DropLocationLabel.Text = "None"
End Sub
Private Sub ListDragTarget_DragLeave(ByVal sender As Object, ByVal e As EventArgs) Handles ListDragTarget.DragLeave
' Reset the label text.
DropLocationLabel.Text = "None"
End Sub
End Class
下面的代码示例演示如何使用 DragDropEffects 枚举指定如何在拖放操作所涉及的控件之间传输数据。 此示例要求窗体包含一个 RichTextBox 控件和一个 ListBox 控件,并且该 ListBox 控件填充了有效的文件名列表。 当用户将文件名拖到控件上时 RichTextBox ,将引发控件的事件 DragEnter 。 在事件处理程序中 Effect , 的 DragEventArgs 属性初始化为 DragDropEffects ,以指示应将文件路径引用的数据复制到 RichTextBox 控件。
private:
void Form1_Load( Object^ /*sender*/, EventArgs^ /*e*/ )
{
// Sets the AllowDrop property so that data can be dragged onto the control.
richTextBox1->AllowDrop = true;
// Add code here to populate the ListBox1 with paths to text files.
}
void listBox1_MouseDown( Object^ sender, System::Windows::Forms::MouseEventArgs^ e )
{
// Determines which item was selected.
ListBox^ lb = (dynamic_cast<ListBox^>(sender));
Point pt = Point(e->X,e->Y);
int index = lb->IndexFromPoint( pt );
// Starts a drag-and-drop operation with that item.
if ( index >= 0 )
{
lb->DoDragDrop( lb->Items[ index ], DragDropEffects::Link );
}
}
void richTextBox1_DragEnter( Object^ /*sender*/, DragEventArgs^ e )
{
// If the data is text, copy the data to the RichTextBox control.
if ( e->Data->GetDataPresent( "Text" ) )
e->Effect = DragDropEffects::Copy;
}
void richTextBox1_DragDrop( Object^ /*sender*/, DragEventArgs^ e )
{
// Loads the file into the control.
richTextBox1->LoadFile( dynamic_cast<String^>(e->Data->GetData( "Text" )), System::Windows::Forms::RichTextBoxStreamType::RichText );
}
private void Form1_Load(object sender, EventArgs e)
{
// Sets the AllowDrop property so that data can be dragged onto the control.
richTextBox1.AllowDrop = true;
// Add code here to populate the ListBox1 with paths to text files.
}
private void listBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Determines which item was selected.
ListBox lb =( (ListBox)sender);
Point pt = new Point(e.X,e.Y);
int index = lb.IndexFromPoint(pt);
// Starts a drag-and-drop operation with that item.
if(index>=0)
{
lb.DoDragDrop(lb.Items[index].ToString(), DragDropEffects.Link);
}
}
private void richTextBox1_DragEnter(object sender, DragEventArgs e)
{
// If the data is text, copy the data to the RichTextBox control.
if(e.Data.GetDataPresent("Text"))
e.Effect = DragDropEffects.Copy;
}
private void richTextBox1_DragDrop(object sender, DragEventArgs e)
{
// Loads the file into the control.
richTextBox1.LoadFile((String)e.Data.GetData("Text"), System.Windows.Forms.RichTextBoxStreamType.RichText);
}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Sets the AllowDrop property so that data can be dragged onto the control.
RichTextBox1.AllowDrop = True
' Add code here to populate the ListBox1 with paths to text files.
End Sub
Private Sub RichTextBox1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles RichTextBox1.DragEnter
' If the data is text, copy the data to the RichTextBox control.
If (e.Data.GetDataPresent("Text")) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
Private Overloads Sub RichTextBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles RichTextBox1.DragDrop
' Loads the file into the control.
RichTextBox1.LoadFile(e.Data.GetData("Text"), System.Windows.Forms.RichTextBoxStreamType.RichText)
End Sub
Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown
Dim Lb As ListBox
Dim Pt As New Point(e.X, e.Y)
Dim Index As Integer
' Determines which item was selected.
Lb = sender
Index = Lb.IndexFromPoint(Pt)
' Starts a drag-and-drop operation with that item.
If Index >= 0 Then
Lb.DoDragDrop(Lb.Items(Index), DragDropEffects.Link)
End If
End Sub
注解
参数 allowedEffects
确定可以执行哪些拖动操作。 如果拖动操作需要与其他进程中的应用程序互操作,则数据应是 (String、 Bitmap或 Metafile) 的基托管类,或者实现 ISerializable 或 IDataObject的对象。
下面描述与拖放操作相关的事件的引发方式以及引发时间。
方法 DoDragDrop 确定当前光标位置下的 控件。 然后,它会检查控件是否是有效的放置目标。
如果控件是有效的拖放目标,则会 GiveFeedback 使用指定的拖放效果引发事件。 有关拖放效果的列表,请参见 DragDropEffects 枚举。
跟踪鼠标光标位置、键盘状态和鼠标按钮状态的更改。
如果键盘或鼠标按钮状态发生更改,则会QueryContinueDrag引发 事件,并根据事件的 QueryContinueDragEventArgs属性的值Action确定是继续拖动、删除数据还是取消操作。
如果 的DragAction
Continue
值为 ,则会DragOver引发事件以继续操作,并使用GiveFeedback新效果引发事件,因此可以设置适当的视觉反馈。 有关有效放置效果的列表,请参见 DragDropEffects 枚举。注意
DragOver和 GiveFeedback 事件是配对的,以便当鼠标在放置目标上移动时,用户将获得有关鼠标位置的最新反馈。
如果 的DragAction
Drop
值为 ,则删除效果值将返回到源,因此源应用程序可以对源数据执行适当的操作;例如,如果操作是移动,则剪切数据。如果 的DragAction
Cancel
值为 ,则DragLeave引发 事件。
注意
方法 DoDragDrop 捕获所有异常,并仅重新引发以下安全或关键异常:
SecurityException
NullReferenceException
StackOverflowException
OutOfMemoryException
ThreadAbortException
ExecutionEngineException
IndexOutOfRangeException
AccessViolationException
另请参阅
适用于
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈