这里是c#初学者。我想让玩家在歌曲结束后立即停止,所以我尝试了下面的解决方案。问题是播放器是歌曲完成后没有停止,我需要手动点击停止按钮,以选择另一首歌。我哪里做错了吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace MusicP
{
public partial class Form1 : Form
{
string command = "";
[DllImport("winmm.dll")]
private static extern long mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength, int hwndCallback);
public Form1()
{
InitializeComponent();
}
public const int MM_MCINOTIFY = 953;
// Override the WndProc function in the form
protected override void WndProc(ref Message m)
{
if (m.Msg == MM_MCINOTIFY)
{
Stop_Click(this, EventArgs.Empty);
}
base.WndProc(ref m);
}
private void Open_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "MP3 Files|*.mp3";
if (ofd.ShowDialog() == DialogResult.OK)
{
string file = ofd.FileName;
label1.Text = ofd.SafeFileName;
command = "open "" + file + "" type MPEGVideo alias MP3";
mciSendString(command, null, 0, 0);
}
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void Play_Click(object sender, EventArgs e)
{
if (label1.Text == "")
{
Open_Click(this, EventArgs.Empty);
}
command = "play MP3 notify";
mciSendString(command, null, 0, 0);
}
private void Stop_Click(object sender, EventArgs e)
{
command = "stop MP3";
mciSendString(command, null, 0, 0);
command = "close MP3";
mciSendString(command, null, 0, 0);
}
private void Pause_Click(object sender, EventArgs e)
{
command = "pause MP3";
mciSendString(command, null, 0, 0);
}
private void Resume_Click(object sender, EventArgs e)
{
command = "resume MP3";
mciSendString(command, null, 0, 0);
}
}
}
非常感谢!
您已经从mciSendString:
中遗漏了窗口的句柄mciSendString(command, null, 0, 0);
应该是这样的:
mciSendString(command, null, 0, (int)this.Handle);
现在Stop_Click被调用了
你可以通过添加一个简单的命令来测试它:
label1.Text = "Stopped";
追加
通知
玩MediaFile
命令:
mciSendString("play MediaFile notify", null, 0, IntPtr.Zero);