c# - 如何拖放到 Windows Media Control

标签 c# .net windows winforms windows-media-player

关于this post , 我想提供将视频文件拖放到 Windows 媒体控件中的可能性,以便它们自动打开。

我已激活 AllowDrop 属性但没有效果。

我读过在 wmp 控件上使用图像控件允许这样做,但我不知道如何在不在视频控件上显示它的情况下做到这一点。

谢谢。

最佳答案

最好、更简洁的解决方案是将嵌入式媒体播放器包装在用户控件中,并确保媒体播放器的 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;
                }
            };
        }
    }
}  

现在您只需将任何媒体文件拖到窗体中央的媒体播放器控件上,它就会接受它作为放置目标并开始播放媒体文件。

关于c# - 如何拖放到 Windows Media Control,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7444449/

相关文章:

c# - 如何从 java 中的文件绘制图形(线)?

c# - 为什么三元运算符不根据要查找的值找到转换类型?

c# - 为什么三元运算符和 if 语句返回不同的结果?

c# - 用C#在Word中用图片替换文本

c# - 动态数据 Web 应用程序给我错误?

Windows 批处理 : download file into current folder

c# - 如何正确处理向字典添加新项目?

c# - C#异步下载文件

windows - 使用powershell查找设置为唤醒电脑的计划任务

php - mysql - 通过 tfs 部署应用程序和数据库更新