【发布时间】:2011-09-16 12:09:30
【问题描述】:
关于this post,我想提供将视频文件拖放到Windows媒体控件中的可能性,以便它们自动打开。
我已激活 AllowDrop 属性,但无效。
我读过在 wmp 控件上使用图像控件可以实现这一点,但如果不显示在视频控件上,我不知道该怎么做。
谢谢。
【问题讨论】:
标签: c# .net windows winforms windows-media-player
关于this post,我想提供将视频文件拖放到Windows媒体控件中的可能性,以便它们自动打开。
我已激活 AllowDrop 属性,但无效。
我读过在 wmp 控件上使用图像控件可以实现这一点,但如果不显示在视频控件上,我不知道该怎么做。
谢谢。
【问题讨论】:
标签: c# .net windows winforms windows-media-player
最好、更简洁的解决方案是将嵌入式媒体播放器包装在用户控件中,并确保媒体播放器的 AllowDrop 属性设置为“false”,并且用户控件的 AllowDrop 属性设置为 true。使嵌入式媒体播放器停靠以填充用户控件,然后将其添加到您的表单中,就像您添加任何用户控件一样。当您在表单中选择用户控件时,您会看到 DragEnter 和 DragDrop 事件按预期公开。像处理普通控件一样处理它们(Cody 提供的代码可以)。您可以在 VB 中的以下链接中看到一个完整的示例(只是不要忘记确保用户控件内的实际嵌入式媒体播放器的 AllowDrop 属性设置为 false,否则它将“隐藏”拖动事件来自用户控件包装器):
http://www.code-magazine.com/article.aspx?quickid=0803041&page=5
但是,如果您只想在窗体上的任意位置处理拖放,包括媒体播放器控件,您需要做的就是处理嵌入式媒体播放器 ActiveX 控件的容器的 DragEnter 和 DragDrop 事件,并使确保实际嵌入控件的 AllowDrop 属性设置为 False,以免从容器中隐藏拖动事件,并且容器的 AllowDrop 设置为 true。
这里有一些代码说明如何使用容器的拖动事件来弥补媒体播放器 ActiveX 控件的拖放事件的不足。
只需创建一个新表单,将其命名为 MainForm,添加对 WMPLib 的所需引用以使 Media Player ActiveX 控件可用于应用程序,调整其大小,使其宽于 320 像素且高于 220 像素,然后粘贴将下面的代码放入您的主表单代码文件中:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using WMPLib;
using AxWMPLib;
namespace YourApplicationNamespace
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
// 40 is the height of the control bar... 320 x 180 is 16:9 aspect ratio
Panel container = new Panel()
{
Parent = this,
Width = 320,
Height = 180 + 40,
AllowDrop = true,
Left = (this.Width - 320) / 2,
Top = (this.Height - 180 - 40) / 2,
};
AxWindowsMediaPlayer player = new AxWindowsMediaPlayer()
{
AllowDrop = false,
Dock = DockStyle.Fill,
};
container.Controls.Add(player);
container.DragEnter += (s, e) =>
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
};
container.DragDrop += (s, e) =>
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
var file = files.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(file))
player.URL = file;
}
};
}
}
}
现在您只需将任何媒体文件拖到表单中心的媒体播放器控件上,它就会接受它作为放置目标并开始播放媒体文件。
【讨论】:
Ok AllowDrop 属性在 MDI 窗体或放置视频播放器控件的窗体中应该为真。 你可以随意放置一个 ListBox 或 Label,然后执行这些操作:
private void filesListBox_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
e.Effect = DragDropEffects.All;
}
}
private void filesListBox_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
//add To Media PLayer
//Play the files
}
//Or Handle the first file in string[] and play that file imediatly
}
【讨论】: