C#WinForm开发笔记——基本控件(二)

一、控件

1、WebBrowser

  • 浏览器控件
    在这里插入图片描述

1>属性

  • Url:导航的网址(在属性栏输入时会自动补全http://)
    在这里插入图片描述

2、ComboBox

  • 下拉框控件:建议以cbo…格式命名
    在这里插入图片描述

1>属性

  • Items:下拉框中的显示内容(可在属性栏中的编辑项、Items以及点击控件上的小三角进行输入)
    在这里插入图片描述
  • DropDownStyle:控制下拉框的外观格式
    在这里插入图片描述
    在这里插入图片描述

2>事件

  • SelectedIndexChanged:当前下拉框中的值被选中的时候发生事件
    在这里插入图片描述

3、ListBox

  • 集合:类似于音乐播放的菜单栏,属性与事件与ComboBox类似
    在这里插入图片描述

1>属性

  • Items:下拉框中的显示内容(可在属性栏中的编辑项、Items以及点击控件上的小三角进行输入)
    在这里插入图片描述

2>事件

  • DoubleClick:双击时触发事件
    在这里插入图片描述

4、Panel

  • 容器:与GroupBox类似
    在这里插入图片描述

5、DataGridView

  • 用于显示表格数据
    在这里插入图片描述
  • 更改中文表名并绑定相关数据列的操作
    在这里插入图片描述
    在这里插入图片描述

二、对话框

  • OpenFileDialog:打开文件对话框
  • SaveFileDialog:保存文件对话框
  • FontDialog:字体对话框
  • ColorDialog:颜色对话框

1、打开文件对话框

在这里插入图片描述

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.IO;

namespace 文本框
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
    
    
            //点击弹出对话框
            OpenFileDialog ofd = new OpenFileDialog();
            //设置对话框标题
            ofd.Title = "请选择需要打开的文档";
            //设置对话框可以多选
            ofd.Multiselect = true;
            //设置对话框的初始目录
            ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";
            //设置对话框的文件类型
            ofd.Filter = "文本文件|*.txt|媒体文件|*.wav|图片文件|*.jpg|所有文件|*.*";
            
            //展示对话框
            ofd.ShowDialog();


            //获得 在打开对话框中  被选中文件的全路径
            string path = ofd.FileName;
            if (path == "")
                return;
            using (FileStream fsRead = new FileStream(path,FileMode.Open,FileAccess.Read))
            {
    
    
                //创建缓冲区
                byte[] buffer =new byte[1024 * 1024 * 5];
                int r = fsRead.Read(buffer, 0, buffer.Length);

                string str = Encoding.Default.GetString(buffer, 0, r);

                textBox1.WordWrap = true;
                textBox1.Text = str;
            }

        }
    }
}

2、保存文件对话框

在这里插入图片描述

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.IO;


namespace 保存文件对话框
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
    
    
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "请选择要保存的路径";
            sfd.InitialDirectory = @"C:\Users\Administrator\Desktop";
            sfd.Filter = "文本文件|*.txt|所有文件|*.*";

            sfd.ShowDialog();

            string path = sfd.FileName;
            if (path == "")
                return;
            using(FileStream fsWrite = new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write))
            {
    
    
                byte[] buffer = Encoding.Default.GetBytes(textBox1.Text);
                fsWrite.Write(buffer, 0, buffer.Length);
            }

            MessageBox.Show("保存成功");
        }
    }
}

3、字体和颜色对话框

在这里插入图片描述

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;

namespace 字体和颜色对话框
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void bntFont_Click(object sender, EventArgs e)
        {
    
    
            FontDialog fd = new FontDialog();
            fd.ShowDialog();
            //将字体对话框选中的字体给到文本框中
            textBox1.Font = fd.Font;
        }

        private void bntColor_Click(object sender, EventArgs e)
        {
    
    
            ColorDialog cd = new ColorDialog();
            cd.ShowDialog();
            //将颜色对话框选中的字体给到文本框中
            textBox1.ForeColor = cd.Color;
        }
    }
}

三、案例代码

1、浏览器

在这里插入图片描述

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;

namespace 浏览器控件
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
    
    
            textBox1.Focus();
            string text = textBox1.Text;
            webBrowser1.Url = new Uri("http://"+text);
        }
    }
}

2、日期选择器

在这里插入图片描述

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;

namespace 日期选择器
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
    
    
            //程序加载的时候,将年份添加到下拉框中
            //获得当前的年份
            int year = DateTime.Now.Year;

            for (int i = year; i >= 1949; i--)
            {
    
    
                cboYear.Items.Add(i + "年");
            }

        }

        /// <summary>
        /// 当年份被选择的时候 加载月份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
    
    
            //添加之前应该清空之前的内容
            cboMonth.Items.Clear();
            for (int i = 1; i <= 12; i++)
            {
    
    
                cboMonth.Items.Add(i + "月");
            }
        }

        /// <summary>
        /// 当月被选中时,加载天
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
    
    
            cboDay.Items.Clear();
            int day = 0;

            //将字符中的年、月剔除    ---用remove不行(没有-1这个索引)
            string strMonth = cboMonth.SelectedItem.ToString().Split(new char[] {
    
     '月'},StringSplitOptions.RemoveEmptyEntries)[0];
            string strYear = cboYear.SelectedItem.ToString().Split(new char[] {
    
     '年' }, StringSplitOptions.RemoveEmptyEntries)[0];

            int month = Convert.ToInt32(strMonth);
            int year = Convert.ToInt32(strYear);

            switch(month)
            {
    
    
                case 4:
                case 6:
                case 9:
                case 11:
                    day = 30;
                    break;
                case 2:
                    if ((year % 400 == 0) || (year % 4 == 0) && (year % 100 != 0))
                        day = 29;
                    else
                        day = 28;
                    break;
                default:
                    day = 31;
                    break;
            }
            for (int i = 1; i <= day; i++)
            {
    
    
                cboDay.Items.Add(i + "日");
            }
        }
    }
}

3、双击显示图片

在这里插入图片描述

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.IO;

namespace ListBox控件
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        string[] path = Directory.GetFiles(@"C:\Users\Administrator\Desktop\Picture");
        List<string> list = new List<string>();
        private void Form1_Load(object sender, EventArgs e)
        {
    
    
            
            for (int i = 0; i < path.Length; i++)
            {
    
    
                //listBox1.Items.Add(path[i]);
                string filePath = Path.GetFileName(path[i]);
                listBox1.Items.Add(filePath);
                list.Add(path[i]);
            }
        }

        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
    
    
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

            //图片路径显示
            pictureBox1.Image = Image.FromFile(path[listBox1.SelectedIndex]);
            //pictureBox1.Image = Image.FromFile(list[listBox1.SelectedIndex]);
        }
    }
}

4、剪刀石头布

  • 设计思路
    在这里插入图片描述
    在这里插入图片描述
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;

namespace 剪刀石头布
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void btnStone_Click(object sender, EventArgs e)
        {
    
    
            string str = "石头";
            PlayGame(str);
        }

        private void PlayGame(string str)
        {
    
    
            lblPlayer.Text = str;

            Player player = new Player();
            int playerNum = player.ShowFist(str);

            Computer cpu = new Computer();
            int cpuNum = cpu.ShowFist();

            lblComputer.Text = cpu.Fist;

            Result result = Caipan.Judge(playerNum, cpuNum);
            lblResult.Text = result.ToString();
        }

        private void btnCut_Click(object sender, EventArgs e)
        {
    
    
            string str = "剪刀";
            PlayGame(str);
        }

        private void btnNo_Click(object sender, EventArgs e)
        {
    
    
            string str = "布";
            PlayGame(str);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
    
    
            lblComputer.Text = "";
            lblPlayer.Text = "";
            lblResult.Text = "";
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 剪刀石头布
{
    
    
    class Player
    {
    
    
        public int ShowFist(string fist)
        {
    
    
            int num = 0;
            switch(fist)
            {
    
    
                case "石头":
                    num = 1;
                    break;
                case "剪刀":
                    num = 2;
                    break;
                case "布":
                    num = 3;
                    break;
            }
            return num;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 剪刀石头布
{
    
    
    class Computer
    {
    
    
        public string Fist
        {
    
    
            get;set;
        }

        public int ShowFist()
        {
    
    
            Random random = new Random();
            int num = random.Next(1, 4);
            switch(num)
            {
    
    
                case 1:
                    Fist = "石头";
                    break;
                case 2:
                    Fist = "剪刀";
                    break;
                case 3:
                    Fist = "布";
                    break;
            }
            return num;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 剪刀石头布
{
    
    
    public enum Result
    {
    
    
        玩家赢,
        平手,
        电脑赢
    }

    class Caipan
    {
    
    

        public static Result Judge(int playerNumber,int cpuNumber)
        {
    
    
            if (playerNumber - cpuNumber == -1 || playerNumber - cpuNumber == 2)
                return Result.玩家赢;
            else if (playerNumber - cpuNumber == 0)
                return Result.平手;
            else
                return Result.电脑赢;
        }

    }
}

5、记事本应用程序

在这里插入图片描述

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

namespace 记事本程序
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
    
    
            //加载程序时隐藏panel
            panel1.Visible = false;
            //取消文本框的自定换行
            textBox1.WordWrap = false;
        }

        private void 隐藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
    
    
            panel1.Visible = false;
        }

        /// <summary>
        /// 点击按钮时也要隐藏panel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
    
    
            panel1.Visible = false;
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
    
    
            panel1.Visible = true;
        }

        List<string> list = new List<string>();
        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
    
    
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择您想要打开的文本文件";
            ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";
            ofd.Multiselect = true;
            ofd.Filter = "文本文件|*.txt|所有文件|*.*";
            ofd.ShowDialog();

            //获得用户选中的文件的全路径
            string path = ofd.FileName;
            //将文件的全路径赋值到泛型集合
            list.Add(path);
            //获取用户打开文件的文件名
            string fileName = Path.GetFileName(path);
            //将文件名放入到ListBox中
            listBox1.Items.Add(fileName);

            if (path == "")
                return;
            using(FileStream fsRead = new FileStream(path,FileMode.Open,FileAccess.Read))
            {
    
    
                byte[] buffer = new byte[1024 * 1024 * 5];
                int r = fsRead.Read(buffer, 0, buffer.Length);
                textBox1.Text = Encoding.Default.GetString(buffer, 0, r);
            }

        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
    
    
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "请选择需要保存的文本文件";
            sfd.InitialDirectory = @"C:\Users\Administrator\Desktop";
            sfd.Filter = "文本文件|*.txt|所有文件|*.*";
            sfd.ShowDialog();

            //获得用户要保存的文件的路径
            string path = sfd.FileName;
            if (path == "")
                return;
            using (FileStream fsWrite = new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write))
            {
    
    
                byte[] buffer = Encoding.Default.GetBytes(textBox1.Text);
                fsWrite.Write(buffer, 0, buffer.Length);
            }
            MessageBox.Show("保存成功");
        }

        private void 自动换行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
    
    
            if(自动换行ToolStripMenuItem.Text=="☆自动换行")
            {
    
    
                textBox1.WordWrap = true;
                自动换行ToolStripMenuItem.Text = "★取消自动换行";
            }
            else
            {
    
    
                textBox1.WordWrap = false;
                自动换行ToolStripMenuItem.Text = "☆自动换行";
            }
        }

        private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
    
    
            FontDialog fd = new FontDialog();
            fd.ShowDialog();
            textBox1.Font = fd.Font;
        }

        private void 颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
    
    
            ColorDialog cd = new ColorDialog();
            cd.ShowDialog();
            textBox1.ForeColor = cd.Color;
        }

        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
    
    
            //获得双击的文件所应用的全路径
            string path = list[listBox1.SelectedIndex];
            using(FileStream fsRead = new FileStream(path,FileMode.Open,FileAccess.Read))
            {
    
    
                byte[] buffer = new byte[1024 * 1024 * 5];
                int r =fsRead.Read(buffer, 0, buffer.Length);
                textBox1.Text = Encoding.Default.GetString(buffer, 0, r);
            }
        }
    }
}

6、音乐播放器

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        List<string> list = new List<string>();
        private void bntOpen_Click(object sender, EventArgs e)
        {
    
    
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "打开您想到打开的音乐文件";
            ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";
            ofd.Filter = "音乐文件|*.wav|文本文件|*.txt|所有文件|*.*";
            ofd.Multiselect = true;
            ofd.ShowDialog();
            //获得我们再文件夹中选择所有文件的全路径
            string[] path = ofd.FileNames;
            for (int i = 0; i < path.Length; i++)
            {
    
    
                listBox1.Items.Add(Path.GetFileName(path[i]));
            }
        }

        SoundPlayer sd = new SoundPlayer();
        /// <summary>
        /// 实现双击播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
    
                
            sd.SoundLocation = list[listBox1.SelectedIndex];
            sd.Play();
        }

        /// <summary>
        /// 点击下一曲
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntDown_Click(object sender, EventArgs e)
        {
    
    
            int index = listBox1.SelectedIndex;
            index++;
            if (index == listBox1.Items.Count)
                index = 0;

            //将改变的索引重新赋值给当前选中项的索引
            listBox1.SelectedIndex = index;
            sd.SoundLocation = list[index];
            sd.Play();

        }

        private void bntUp_Click(object sender, EventArgs e)
        {
    
    
            int index = listBox1.SelectedIndex;
            index--;
            if (index == 0)
                index = listBox1.Items.Count - 1;
            listBox1.SelectedIndex = index;
            sd.SoundLocation = list[index];
            sd.Play();
        }
    }
}

7、酷狗播放器简易版

在这里插入图片描述

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

namespace 播放器
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
    
    
            musicPlayer.Ctlcontrols.play();
        }

        private void button6_Click(object sender, EventArgs e)
        {
    
    
            musicPlayer.Ctlcontrols.pause();
        }

        /// <summary>
        /// 播放、暂停
        /// </summary>
        bool IsNew = true;
        private void btnPlayorStop_Click(object sender, EventArgs e)
        {
    
    
            
            if(btnPlayorStop.Text=="播放")
            {
    
    
                //获得选中的歌曲
                if (IsNew==true)
                {
    
    
                    //获得选择的音乐,让音乐重头播放
                    musicPlayer.URL = listPath[listBox1.SelectedIndex];
                }
                IsExistLrc(listPath[listBox1.SelectedIndex]);
                musicPlayer.Ctlcontrols.play();
                btnPlayorStop.Text = "暂停";
            }
            else if(btnPlayorStop.Text=="暂停")
            {
    
    
                musicPlayer.Ctlcontrols.pause();
                btnPlayorStop.Text = "播放";
                IsNew = false;
            }
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
    
    
            musicPlayer.Ctlcontrols.stop();
            btnPlayorStop.Text = "播放";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
    
    
            musicPlayer.settings.autoStart = false;
            label1.Image = Image.FromFile(@"C:\Users\Administrator\Desktop\静音.png");
        }

        /// <summary>
        /// 添加音乐文件
        /// </summary>
        List<string> listPath = new List<string>();
        private void button5_Click(object sender, EventArgs e)
        {
    
    
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择你要播放的文件";
            ofd.InitialDirectory = @"D:\KuGou\";
            ofd.Filter = "音乐文件|*.mp3|所有文件|*.*";
            ofd.Multiselect = true;
            ofd.ShowDialog();

            string[] path = ofd.FileNames;
            for (int i = 0; i < path.Length; i++)
            {
    
    
                listPath.Add(path[i]);

                listBox1.Items.Add(Path.GetFileName(path[i]));
            }
        }

        /// <summary>
        /// 双击播放音乐
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
    
    
            //如果listbox中无文件
            if(listBox1.Items.Count==0)
            {
    
    
                MessageBox.Show("请先选择文件");
                return;
            }
            try
            {
    
    
                musicPlayer.URL = listPath[listBox1.SelectedIndex];
                musicPlayer.Ctlcontrols.play();
                btnPlayorStop.Text = "暂停";
                IsExistLrc(listPath[listBox1.SelectedIndex]);

            }
            catch {
    
     }
        }

        /// <summary>
        /// 下一首
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
    
    
            label2.Text = "";
            int index = listBox1.SelectedIndex;
            listBox1.SelectedIndices.Clear();
            index++;
            if(index==listBox1.Items.Count)
            {
    
    
                index = 0;
            }
            listBox1.SelectedIndex = index;
            IsExistLrc(listPath[listBox1.SelectedIndex]);
            musicPlayer.URL = listPath[index];
            musicPlayer.Ctlcontrols.play();
        }

        /// <summary>
        /// 上一首
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
    
    
            label2.Text = "";
            int index = listBox1.SelectedIndex;
            listBox1.SelectedIndices.Clear();
            index--;
            if(index<0)
            {
    
    
                index = listBox1.Items.Count - 1;
            }
            listBox1.SelectedIndex = index;
            IsExistLrc(listPath[listBox1.SelectedIndex]);
            musicPlayer.URL = listPath[index];
            musicPlayer.Ctlcontrols.play();
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
    
    
            int count = listBox1.SelectedItems.Count;
            for (int i = 0; i < count; i++)
            {
    
    
                //先删集合
                listPath.RemoveAt(listBox1.SelectedIndex);
                //再删listbox
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {
    
    
            if(label1.Tag.ToString()=="1")
            {
    
    
                musicPlayer.settings.mute = true;
                label1.Image = Image.FromFile(@"C:\Users\Administrator\Desktop\放音.png");
                label1.Tag = "2";
            }
            else if(label1.Tag.ToString()=="2")
            {
    
    
                musicPlayer.settings.mute = false;
                label1.Image = Image.FromFile(@"C:\Users\Administrator\Desktop\静音.png");
                label1.Tag = "1";
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
    
    
            musicPlayer.settings.volume++;
        }

        private void button8_Click(object sender, EventArgs e)
        {
    
    
            musicPlayer.settings.volume--;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
    
    
            try
            {
    
    
                //如果播放器的状态等于正在播放中
                if (musicPlayer.playState == WMPLib.WMPPlayState.wmppsPlaying)
                {
    
    
                    lblInformation.Text = musicPlayer.currentMedia.duration.ToString() + "\r\n" + musicPlayer.currentMedia.durationString.ToString() + "\r\n" + musicPlayer.Ctlcontrols.currentPosition.ToString() + "\r\n" + musicPlayer.Ctlcontrols.currentPositionString.ToString();
                    double d1 = musicPlayer.currentMedia.duration;
                    double d2 = musicPlayer.Ctlcontrols.currentPosition + 1;
                    //如果当前音乐的总时间小于等于当前播放的时间
                    if (d1 <= d2)
                    {
    
    
                        int index = listBox1.SelectedIndex;
                        listBox1.SelectedIndices.Clear();
                        index++;
                        if (index == listBox1.Items.Count)
                        {
    
    
                            index = 0;
                        }
                        listBox1.SelectedIndex = index;
                        IsExistLrc(listPath[index]);
                        musicPlayer.URL = listPath[index];
                        musicPlayer.Ctlcontrols.play();
                    }
                }
            }
            catch {
    
     }
        }

        void IsExistLrc(string songPath)
        {
    
    
            try
            {
    
    
                label2.Text = "";
                string songLrcPath = Path.ChangeExtension(songPath, "lrc");
                if (File.Exists(songLrcPath))
                {
    
    
                    //读取歌词文件
                    string[] lrcText = File.ReadAllLines(songLrcPath, Encoding.Default);
                    //格式化歌词
                    FormatLrc(lrcText);
                }
                else
                {
    
    
                    label2.Text = "-----------歌词未找到------------";
                }
            }
            catch {
    
     }
        }


        List<double> listTime = new List<double>();
        List<string> listSong = new List<string>();
        void FormatLrc(string[] lrcText)
        {
    
    
            listTime.Clear();
            listSong.Clear();
            for (int i = 0; i < lrcText.Length; i++)
            {
    
    
                if (lrcText[i] != "")
                {
    
    
                    //[00:11.31]不用太刻意 来就是兄弟
                    string[] lrcTemp = lrcText[i].Split(new char[] {
    
     '[', ']' }, StringSplitOptions.RemoveEmptyEntries);
                    //00:11.31   lrcTemp[0]
                    //不用太刻意 来就是兄弟  lrcTemp[1]
                    string[] lrcNewTemp = lrcTemp[0].Split(new char[] {
    
     ':' }, StringSplitOptions.RemoveEmptyEntries);
                    //00
                    //11.31
                    if (lrcTemp.Length>1)
                    {
    
    
                        double time = double.Parse(lrcNewTemp[0]) * 60 + double.Parse(lrcNewTemp[1]);
                        //把截取出的时间存储到泛型集合中
                        listTime.Add(time);
                        //把截取的歌词存储到泛型集合中
                        listSong.Add(lrcTemp[1]);
                    }
    
                }
                else
                    continue;
            }
        }

        /// <summary>
        /// 播放歌词
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
    
    
            try
            {
    
    
                for (int i = 0; i < listTime.Count; i++)
                {
    
    
                    if (musicPlayer.Ctlcontrols.currentPosition >= listTime[i] && musicPlayer.Ctlcontrols.currentPosition < listTime[i + 1])
                    {
    
    
                        label2.Text = listSong[i];
                    }
                }
            }
            catch {
    
     }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Lcl_huolitianji/article/details/121673130