Riz*_*Riz 9 c# wpf drag-and-drop
我有一个小的 WPF 应用程序,它有一个带有图像控件的窗口。图像控件显示来自文件系统的图像。我希望用户能够将图像拖放到桌面或任何地方进行保存。它工作正常。
但是我想在用户拖动鼠标光标时显示小图像缩略图。就像我们将图像从 Windows 文件资源管理器拖到其他地方一样。如何实现?
当前拖放行为
期望的行为
这是我的 XAML 代码
<Grid>
<Image x:Name="img" Height="100" Width="100" Margin="100,30,0,0"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)
这是 C# 代码
public partial class MainWindow : Window
{
string imgPath;
Point start;
bool dragStart = false;
public MainWindow()
{
InitializeComponent();
imgPath = "C:\\Pictures\\flower.jpg";
ImageSource imageSource = new BitmapImage(new Uri(imgPath));
img.Source = imageSource;
window.PreviewMouseMove += Window_PreviewMouseMove;
window.PreviewMouseUp += Window_PreviewMouseUp;
window.Closing += Window_Closing;
img.PreviewMouseLeftButtonDown += Img_PreviewMouseLeftButtonDown;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
window.PreviewMouseMove -= Window_PreviewMouseMove;
window.PreviewMouseUp -= Window_PreviewMouseUp;
window.Closing -= Window_Closing;
img.PreviewMouseLeftButtonDown -= Img_PreviewMouseLeftButtonDown;
}
private void Window_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (!dragStart) return;
if (e.LeftButton != MouseButtonState.Pressed)
{
dragStart = false; return;
}
Point mpos = e.GetPosition(null);
Vector diff = this.start - mpos;
if (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance &&
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)
{
string[] file = { imgPath };
DataObject d = new DataObject();
d.SetData(DataFormats.Text, file[0]);
d.SetData(DataFormats.FileDrop, file);
DragDrop.DoDragDrop(this, d, DragDropEffects.Copy);
}
}
private void Img_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.start = e.GetPosition(null);
dragStart = true;
}
private void Window_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
dragStart = false;
}
}
Run Code Online (Sandbox Code Playgroud)
正式地,您应该使用IDragSourceHelper接口将预览位图添加到拖放操作中。
不幸的是,该接口使用IDataObject::SetData 方法,该方法并未由 .NET DataObject 类在 COM 级别实现,而仅在 .NET 级别实现。
解决方案是使用SHCreateItemFromParsingName 函数和 IShellItem::BindToHandler 方法,重新使用 Shell 提供的 IDataObject,而不是任何 Shell Item(此处为文件)。
请注意,这些函数会自动添加剪贴板格式(如 FileDrop),但我们仍然必须使用 IDragSourceHelper 来添加预览图像。
您可以这样使用它:
...
// get IDataObject from the Shell so it can handle more formats
var dataObject = DataObjectUtilities.GetFileDataObject(imgPath);
// add the thumbnail to the data object
DataObjectUtilities.AddPreviewImage(dataObject, imgPath);
// start d&d
DragDrop.DoDragDrop(this, dataObject, DragDropEffects.All);
...
Run Code Online (Sandbox Code Playgroud)
这是代码:
public static class DataObjectUtilities
{
public static void AddPreviewImage(System.Runtime.InteropServices.ComTypes.IDataObject dataObject, string imgPath)
{
if (dataObject == null)
throw new ArgumentNullException(nameof(dataObject));
var ddh = (IDragSourceHelper)new DragDropHelper();
var dragImage = new SHDRAGIMAGE();
// note you should use a thumbnail here, not a full-sized image
var thumbnail = new System.Drawing.Bitmap(imgPath);
dragImage.sizeDragImage.cx = thumbnail.Width;
dragImage.sizeDragImage.cy = thumbnail.Height;
dragImage.hbmpDragImage = thumbnail.GetHbitmap();
Marshal.ThrowExceptionForHR(ddh.InitializeFromBitmap(ref dragImage, dataObject));
}
public static System.Runtime.InteropServices.ComTypes.IDataObject GetFileDataObject(string filePath)
{
if (filePath == null)
throw new ArgumentNullException(nameof(filePath));
Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(filePath, null, typeof(IShellItem).GUID, out var item));
Marshal.ThrowExceptionForHR(item.BindToHandler(null, BHID_DataObject, typeof(System.Runtime.InteropServices.ComTypes.IDataObject).GUID, out var dataObject));
return (System.Runtime.InteropServices.ComTypes.IDataObject)dataObject;
}
private static readonly Guid BHID_DataObject = new Guid("b8c0bd9f-ed24-455c-83e6-d5390c4fe8c4");
[DllImport("shell32", CharSet = CharSet.Unicode)]
private static extern int SHCreateItemFromParsingName(string path, System.Runtime.InteropServices.ComTypes.IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IShellItem ppv);
[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem
{
[PreserveSig]
int BindToHandler(System.Runtime.InteropServices.ComTypes.IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid bhid, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);
// other methods are not defined, we don't need them
}
[ComImport, Guid("4657278a-411b-11d2-839a-00c04fd918d0")] // CLSID_DragDropHelper
private class DragDropHelper
{
}
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
private struct SIZE
{
public int cx;
public int cy;
}
// https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/ns-shobjidl_core-shdragimage
[StructLayout(LayoutKind.Sequential)]
private struct SHDRAGIMAGE
{
public SIZE sizeDragImage;
public POINT ptOffset;
public IntPtr hbmpDragImage;
public int crColorKey;
}
// https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-idragsourcehelper
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("DE5BF786-477A-11D2-839D-00C04FD918D0")]
private interface IDragSourceHelper
{
[PreserveSig]
int InitializeFromBitmap(ref SHDRAGIMAGE pshdi, System.Runtime.InteropServices.ComTypes.IDataObject pDataObject);
[PreserveSig]
int InitializeFromWindow(IntPtr hwnd, ref POINT ppt, System.Runtime.InteropServices.ComTypes.IDataObject pDataObject);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
894 次 |
最近记录: |