winform音乐播放器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanlong360599336/article/details/7555656

先展示效果图:

首先,我做得这个音乐播放器有点杂乱无章,因为在做之前没有做规划,只是想到什么就加什么功能,希望大家见谅。这个播放器除了基本的播放功能外,还增加了程序自启动功能,截图功能,及截图浏览功能等。

 

最左边的这个是主窗体,实现音乐播放功能的,右边的这个是用来展示截图功能的副窗体,可以点击收起截图按钮,右边的这个副窗体就能隐藏掉了,如果再想看截图的效果,点击就会弹出右边的窗体了。总共建了2个窗体。

 

我们就开始实现音乐播放器效果把,上代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Drawing.Imaging;
using Microsoft.Win32;

//########################################
//########################################
//########################################
//######///////////////////////////#######
//######编码人:万龙////////////////#######
//######开始时间:2012年5月5日//////#######
//######最近更新时间:2012年5月6日//#######
//######///////////////////////////#######
//########################################
//########################################
//########################################
//########################################


namespace MusicPlay
{
    public partial class Form1 : Office2007Form
    {
        #region 窗体出现动画API
        private const int AW_HOR_POSITIVE = 0x0001;//自左向右显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        private const int AW_HOR_NEGATIVE = 0x0002;//自右向左显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        private const int AW_VER_POSITIVE = 0x0004;//自顶向下显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        private const int AW_VER_NEGATIVE = 0x0008;//自下向上显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志该标志
        private const int AW_CENTER = 0x0010;//若使用了AW_HIDE标志,则使窗口向内重叠;否则向外扩展
        private const int AW_HIDE = 0x10000;//隐藏窗口
        private const int AW_ACTIVE = 0x20000;//激活窗口,在使用了AW_HIDE标志后不要使用这个标志
        private const int AW_SLIDE = 0x40000;//使用滑动类型动画效果,默认为滚动动画类型,当使用AW_CENTER标志时,这个标志就被忽略
        private const int AW_BLEND = 0x80000;//使用淡入淡出效果
        [DllImportAttribute("user32.dll")]
        private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
        #endregion
        public delegate void DeleCurrentTime(int Currtime);
        WLMusicDll.musicClass mp=new WLMusicDll.musicClass();
        System.Windows.Forms.Timer timer;
        System.Windows.Forms.ToolTip tooltip;
        ContextMenuStrip cms;
        ContextMenuStrip cmsCur;
        string musicName=string.Empty;

        public Form1()
        {
            
            InitializeComponent();
            tool();
            timer = new System.Windows.Forms.Timer();
            timer.Interval = 1000;
            timer.Enabled = true;
            AnimateWindow(this.Handle, 1000, AW_SLIDE | AW_ACTIVE | AW_VER_NEGATIVE);
           
            constMusicLoad();
            cmsCur = new ContextMenuStrip();
            notifyIcon1.ContextMenuStrip = cmsCur;
            cmsCur.Items.AddRange(new ToolStripItem[] { new ToolStripMenuItem("显示"), new ToolStripMenuItem("退出") });
            foreach (ToolStripMenuItem cmsClick in cmsCur.Items)
            {
                if (cmsClick.Text.Equals("显示"))
                {
                    cmsClick.Click += new EventHandler(cmsClick_Click);
                }
                if (cmsClick.Text.Equals("退出"))
                {
                    cmsClick.Click += new EventHandler(cmsClick_Click1);
                }
            }
            this.listView1.DoubleClick += new EventHandler(listView1_DoubleClick);
            pictureBox1.DoubleClick += new EventHandler(pictureBox1_DoubleClick);
            cms = new ContextMenuStrip();
            pictureBox2.ContextMenuStrip = cms;
            cms.Items.AddRange(new ToolStripItem[]{new ToolStripMenuItem("图片保存") ,new ToolStripMenuItem("打开保存文件夹")});
            foreach(ToolStripMenuItem tsmi in cms.Items)
            {
                if(tsmi.Text.Equals("图片保存"))
                {
                    tsmi.Click+=new EventHandler(tsmi_Click);
                }
                if (tsmi.Text.Equals("打开保存文件夹"))
                {
                    tsmi.Click +=new EventHandler(tsmi_Click1);
                }
            }
            pictureBox2.DoubleClick += new EventHandler(pictureBox2_DoubleClick);
        }

        void cmsClick_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }
        void cmsClick_Click1(object sender, EventArgs e)
        {
            Application.Exit();
            System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
            process.Kill();

        }
        void tsmi_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "PNG图片(*.PNG)|*.png";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                pictureBox2.BackgroundImage.Save(sfd.FileName, ImageFormat.Png);
                MessageBox.Show("图片保存成功!");
            }
        }
        void tsmi_Click1(object sender, EventArgs e)
        {
            string dir = AppDomain.CurrentDomain.BaseDirectory+"Pic";
            if (Directory.Exists(dir))
            { 
                System.Diagnostics.Process.Start(dir);
            }
            else
            {
                Directory.CreateDirectory(dir);
                System.Diagnostics.Process.Start(dir);
            }
            
        }
        void pictureBox2_DoubleClick(object sender, EventArgs e)
        {
            if (this.pictureBox2.BackgroundImage != null)
            {
                Clipboard.SetImage(this.pictureBox2.BackgroundImage);
                MessageBox.Show("图片已复制到剪贴板", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                string dir = AppDomain.CurrentDomain.BaseDirectory + "Pic";
                string pic = dir + "\\" + DateTime.Now.ToString("HH_ss") + ".png";
                if (Directory.Exists(dir))
                {
                    pictureBox2.BackgroundImage.Save(pic);
                }
                else
                {
                    Directory.CreateDirectory(dir);
                    pictureBox2.BackgroundImage.Save(pic);
                }
            }
        }
        void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "图片格式(*.bmp;*.jpg;*.gif;*.png)|*.bmp;*.jpg;*.gif;*.png";
            if(ofd.ShowDialog()==DialogResult.OK)
            {
                pictureBox1.Image = new Bitmap(ofd.FileName);
            }
        }
        void tool()
        {
            tooltip =new System.Windows.Forms.ToolTip();
            tooltip.SetToolTip(upMove,"上一首");
            tooltip.SetToolTip(startPlay, "播放");
            tooltip.SetToolTip(downMove, "下一首");
        }
        void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (this.listView1.Items.Count > 0)
            {
                timer.Enabled = true;
                timer.Start();
                mp=new WLMusicDll.musicClass();
                mp.FileName = listView1.SelectedItems[0].SubItems[2].Text;
                listView1.Tag = listView1.SelectedItems[0].Text;
                progressBarX1.Maximum = mp.Duration;
                mp.play();
                MuscName.Text = MuscName.Tag.ToString().Split(':')[0] + ":[" + listView1.SelectedItems[0].Text + "]";
                
            }
        }
        
        void constMusicLoad()
        {
            mp = new WLMusicDll.musicClass();
            musicName = "黑蝙蝠中队.mp3";
            string fileName=AppDomain.CurrentDomain.BaseDirectory + musicName;
            if (File.Exists(fileName))
            {
                mp.FileName = fileName;
                musicList(musicName, mp.Duration, fileName);
                mp.play();
                musicInfo(musicName.Split('.')[0]);
            }
            else
            {
                return;
            }
           
        }
        void musicList(string name, int totalTime, string fileDir)
        {
            string Time = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(totalTime).ToString("mm:ss");
            ListViewItem lvi = new ListViewItem();
            lvi.Text = "[默认]"+name.Split('.')[0].ToString();
            lvi.SubItems.AddRange(new string[] { Time, fileDir });
            listView1.Items.Add(lvi);
        }

        void musicInfo(string name)
        {
            
            MuscName.Text = MuscName.Tag.ToString().Split(':')[0] + ":[" + name + "]";
            progressBarX1.Maximum = mp.Duration;
            timer.Tick += (sender, e) => {
                currentTime.Text = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(mp.CurrentPosition).ToString("mm:ss");
                progressBarX1.Value = mp.CurrentPosition;  
                    if (mp.IsEnd())
                    {
                        timer.Stop();
                        timer.Enabled = false;
                        currentTime.Text = "00:00";
                        progressBarX1.Value = 0;
                        startPlay.Text = "▶";
                        playState.Text = "状态:停止";
                    }
                    else
                    {
                        timer.Start();
                        tooltip.SetToolTip(startPlay, "暂停");
                        startPlay.Text = "||";
                        playState.Text = "状态:播放";
                    }
             
                
            };
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            
            Application.Exit();
            System.Diagnostics.Process process =System.Diagnostics.Process.GetCurrentProcess();
            process.Kill();
        }
        /// <summary>
        /// 右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        int i = 0;
        private void fileControl(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = sender as ToolStripMenuItem;
            string name = tsmi.Name;
            
            switch(name)
            {
                case "AddFile":
                    OpenFileDialog ofd = new OpenFileDialog();
                    ofd.Multiselect = true;
                    ofd.Title = "搜索音乐文件";
                    ofd.Filter = @"所有音乐格式格式(*.mp3;*.wma;*.wav;*.mid;*.rmi;*.rm;*.ra)|*.mp3;*.wma;*.wav;*.mid;*.rmi;*.rm;*.ra";
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        
                        foreach (string fileName in ofd.FileNames)
                        {
                            mp = new WLMusicDll.musicClass();
                            mp.FileName = fileName;
                            string totaltime=new DateTime(1970,1,1,0,0,0).AddSeconds(mp.Duration).ToString("mm:ss");
                            ListViewItem lvi = new ListViewItem();
                            lvi.Text = i.ToString() + "." + Path.GetFileNameWithoutExtension(fileName); ;
                            lvi.SubItems.AddRange(new string[] { totaltime, fileName });
                            listView1.Items.Add(lvi);
                            i++;
                        }
                       
                    }
                    break;
                case "AddFold":
                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    if(fbd.ShowDialog()==DialogResult.OK)
                    {
                        DirectoryInfo dif = new DirectoryInfo(fbd.SelectedPath);
                       foreach(FileInfo file in dif.GetFiles("*.mp3"))
                       {
                           try
                           {
                               mp = new WLMusicDll.musicClass();
                               mp.FileName = file.FullName;
                               string totaltime = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(mp.Duration).ToString("mm:ss");
                               ListViewItem lvi = new ListViewItem();
                               lvi.Text = i.ToString() + "." + Path.GetFileNameWithoutExtension(file.FullName); ;
                               lvi.SubItems.AddRange(new string[] { totaltime, file.FullName });
                               listView1.Items.Add(lvi);
                               i++;
                           }
                           catch (Exception ex)
                           {
                               MessageBox.Show("音乐格式不支持..");
                           }
                       }
                      
                    }
                    break;
                case "DeleteFile": 
                    foreach(ListViewItem lvi in listView1.SelectedItems)
                    {
                        lvi.Remove();
                    }
                    break;
                default: break;
            }
        }
        /// <summary>
        /// 音乐播放控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void musicClick(object sender, EventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                string name = btn.Text;
                mp = new WLMusicDll.musicClass();
                string itemId = listView1.Tag.ToString().Split('.')[0].ToString();
                switch (name)
                {
                    case "▶":
                        tooltip.SetToolTip(startPlay, "暂停");
                        btn.Text = "||";
                        timer.Start();
                        mp.play();
                        break;
                    case "||":
                        tooltip.SetToolTip(startPlay, "开始");
                        btn.Text = "▶";
                        timer.Stop();
                        mp.Puase();
                        break;
                    case "☜":
                        try
                        {
                            if (listView1.SelectedItems[0].Text.Split('.')[0].ToString().Equals("[默认]黑蝙蝠中队"))
                            {
                                musicName = "黑蝙蝠中队.mp3";
                                mp.FileName = AppDomain.CurrentDomain.BaseDirectory + musicName;
                            }
                            else
                            {
                                mp.FileName = listView1.Items[Convert.ToInt32(itemId) - 1].SubItems[2].Text;
                            }
                            progressBarX1.Maximum = mp.Duration;
                            mp.play();
                            MuscName.Text = MuscName.Tag.ToString().Split(':')[0] + ":[" + listView1.Items[Convert.ToInt32(itemId) - 1].Text + "]";
                        }
                        catch { }
                        break;
                    case "☞":
                        try
                        {
                            if (Convert.ToInt32(itemId) < listView1.Items.Count-1)
                            {
                                mp.FileName = listView1.Items[Convert.ToInt32(itemId)+1].SubItems[2].Text;
                            }
                            else
                            {
                                mp.FileName = listView1.Items[listView1.Items.Count - 1].SubItems[2].Text;
                            }
                            progressBarX1.Maximum = mp.Duration;
                            mp.play();
                            MuscName.Text = MuscName.Tag.ToString().Split(':')[0] + ":[" + listView1.Items[Convert.ToInt32(itemId) + 1].Text + "]";
                        }
                        catch { }
                        break;
                    default: break;
                }
            }
            catch { }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            AnimateWindow(this.Handle, 1000, AW_SLIDE | AW_ACTIVE | AW_VER_POSITIVE);
        }
        /// <summary>
        /// 截图界面的缩放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text.Equals("展开截图"))
            {
                
                button1.Text = "收起截图";
                this.Width = 907;
                AnimateWindow(pictureBox2.Handle, 1000, AW_SLIDE | AW_ACTIVE | AW_HOR_POSITIVE); 
                AnimateWindow(pictureBox3.Handle, 1000, AW_SLIDE | AW_ACTIVE | AW_VER_POSITIVE);
                AnimateWindow(label1.Handle, 1000, AW_SLIDE | AW_ACTIVE | AW_VER_POSITIVE);
                AnimateWindow(button5.Handle, 1000, AW_SLIDE | AW_ACTIVE | AW_VER_NEGATIVE);
                AnimateWindow(button2.Handle, 1000, AW_SLIDE | AW_ACTIVE | AW_VER_NEGATIVE);
                AnimateWindow(button3.Handle, 1000, AW_SLIDE | AW_ACTIVE | AW_VER_NEGATIVE);
                AnimateWindow(button4.Handle, 1000, AW_SLIDE | AW_ACTIVE | AW_VER_NEGATIVE);
                
                pictureBox2.Visible = true;
                pictureBox3.Visible = true;
                label1.Visible = true;
                button5.Visible = true;
                button2.Visible = true;
                button3.Visible = true;
                button4.Visible = true;
            }
            else
            {

                pictureBox2.Visible = false;
                pictureBox3.Visible = false;
                label1.Visible = false;
                button5.Visible = false;
                button2.Visible = false;
                button3.Visible = false;
                button4.Visible = false;
                this.Width = 296;
                button1.Text = "展开截图";
            }
           
        }
        Image image;
        public Image Snap(int x, int y, int width, int height)
        {
            pictureBox2.BackgroundImageLayout = ImageLayout.Stretch;
            image = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(image);
            g.CopyFromScreen(x, y, 0, 0, new System.Drawing.Size(width, height));
            if (width < pictureBox2.Width && height < pictureBox2.Height)
                pictureBox2.BackgroundImageLayout = ImageLayout.Stretch;
            pictureBox2.BackgroundImage = image;
            return image;
        }
        /// <summary>
        /// 全屏截图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                th.Suspend();
            }
            catch { }
                pictureBox2.BackgroundImage = null;
                if (radioButton1.Checked)
                {
                    radioButton1.Checked = false;
                    this.Hide();
                    Snap(0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

                    this.Show();
                    
                }
                else
                {
                    return;
                }
            
        }
        /// <summary>
        /// 局部截图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                th.Suspend();
            }
            catch { }
                pictureBox2.BackgroundImage = null;
                if (radioButton2.Checked)
                {
                    radioButton2.Checked = false;
                    this.Hide();
                    Form3 f3 = new Form3(this);
                    f3.ShowDialog();
                }
                else
                {
                    return;
                }
           
            
        }
        /// <summary>
        /// 开机自启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox1.Checked)
            {
                try
                {
                    string proPath = Application.ExecutablePath;
                    RegistryKey reg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                    reg.SetValue(Path.GetFileNameWithoutExtension(proPath), proPath);
                    reg.Close();
                }
                catch(Exception ex)
                {
                    MessageBox.Show("启动设置异常:" + ex.Message);
                }
            }
            else
            {
                try
                {

                    string proPath = Application.ExecutablePath;
                    RegistryKey reg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                    reg.DeleteValue(Path.GetFileNameWithoutExtension(proPath));
                    reg.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("启动设置异常:" + ex.Message);
                }
            }
        }
        Thread th;
        Thread upTh;
        Thread downTh;
        string dir = string.Empty;
        private void btnClick(object sender, EventArgs e)
        {
            dir = AppDomain.CurrentDomain.BaseDirectory + "Pic";
            if (Directory.Exists(dir))
            {
                if (Directory.GetFiles(dir).Length > 0)
                {
                    Button btn = sender as Button;
                    string name = btn.Text;
                    switch (name)
                    {
                        case "上移":
                            upTh = new Thread(upMoveMain);
                            upTh.IsBackground = true;
                            upTh.Start();
                            break;
                        case "开始":
                            th = new Thread(startPic);
                            th.IsBackground = true;
                            th.Start();
                            break;
                        case "停止":
                            try
                            {
                                th.Suspend();
                            }
                            catch { }
                            break;
                        case "下移":
                            downTh = new Thread(downMoveMain);
                            downTh.IsBackground = true;
                            downTh.Start();
                            break;
                        default: break;

                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                return;
            }
        }
        int num = 0;
        void startPic()
        {

            try
            {

                while (num < Directory.GetFiles(dir).Length - 1)
                {
                    pictureBox2.BackgroundImage = new Bitmap(Directory.GetFiles(dir)[num].ToString());
                    num++;
                    Thread.Sleep(2000);
                    if (num >= Directory.GetFiles(dir).Length - 1)
                    {
                        num = 0;
                    }

                }

            }
            catch (Exception ex)
            {
                MessageBoxEx.Show("图片已完,请继续..", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
           
        }
        void upMoveMain()
        {

            try
            {
                if (num > 0)
                {
                    num--;
                    pictureBox2.BackgroundImage = new Bitmap(Directory.GetFiles(dir)[num].ToString());
                }
                else
                {
                    return;
                }
            }
            catch { }
            
        }
        void downMoveMain()
        {

            try
            {
                if (num < Directory.GetFiles(dir).Length - 1)
                {
                    num++;
                    pictureBox2.BackgroundImage = new Bitmap(Directory.GetFiles(dir)[num].ToString());
                }
                else
                {
                    return;
                }
            }catch{}
            
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked)
            {
                if (listView1.Items.Count > 0)
                {
                    
                        Random rd = new Random();
                        int i = rd.Next(listView1.Items.Count);
                        mp = new WLMusicDll.musicClass();
                        mp.FileName = listView1.Items[i].SubItems[2].Text;
                        progressBarX1.Maximum = mp.Duration;
                        mp.play();
                        MuscName.Text = MuscName.Tag.ToString().Split(':')[0] + ":[" + listView1.Items[i].Text + "]";
                   
                }
                else
                {
                    return;
                }
            }
            else
            {
                return;
            }
        }



    }
}


接下来就是实现截图功能的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MusicPlay
{
    public partial class Form3 : Form
    {
        Graphics gra;
        bool isDown = false;
        Form1 f;
        public Form3(Form1 f1)
        {
            InitializeComponent();
            f = f1;
            this.Cursor = Cursors.Cross;
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer|ControlStyles.ResizeRedraw|ControlStyles.UserPaint, true);
        }
        int x=0; int y=0;
        private void Form3_MouseDown(object sender, MouseEventArgs e)
        {
            x = e.X;
            y = e.Y;
            if (e.Button == MouseButtons.Left)
            {
                isDown = true;
            }
            else
            {
                f.Show();
            }
        }
        int height = 0; int width = 0;
        private void Form3_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDown)
            {
                width =Math.Abs(e.X - x);
                height = Math.Abs(e.Y-y);
                gra = this.CreateGraphics();
                gra.Clear(BackColor);
                gra.FillRectangle(Brushes.CornflowerBlue, x < e.X ? x : e.X, y < e.Y ? y : e.Y, width, height);
                //gra.Dispose();
            }
        }

        private void Form3_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                this.Close();
                if (e.Button == MouseButtons.Left)
                {
                    f.Snap(x < e.X ? x : e.X, y < e.Y ? y : e.Y, width, height);
                }
                else
                {
                    return;
                }
                f.Show();
            }
            catch  { }
        }
    }
}


 

扫描二维码关注公众号,回复: 3817093 查看本文章

由于控件方面不好描述,大家只能将就着看看代码,用心去理解了。有什么不懂得给我留言!!

 

音乐播放器DEMO

猜你喜欢

转载自blog.csdn.net/wanlong360599336/article/details/7555656