SoFunction
Updated on 2025-03-07

C# based music player main Form implementation code

This article describes the main Form code for a music player written by C#. There are some small tips in it that are quite good. I'm sharing them for your reference. It contains the player background settings, thread definition, call to read file directory method, play time counter, set LV background, get play songs, play button, switch play or pause, switch songs to the next song, call the song cutting method, display playlist, lyrics, play form minimize hidden to tray settings, progress bar scrolling module, delete files from song list, etc. In addition, each functional template has relatively detailed annotations for everyone to read and understand.

The main code of the program is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
namespace MyMusicBox
{
  public partial class MainForm : Form
  {
    public MainForm()
    {
      InitializeComponent();
      SetStyle(, true);
      SetStyle(, true);
      SetStyle(, true);
      SetStyle(, true); 
     
    }
    Song mySong = null;//The song object played    ListViewItem itemLrc;//Open the lyrics path item    Bitmap bm ;// Used to dynamically set LV background    public SavingInfo sa = null;//Permanent information class    Thread thread;//Background thread 
    #region Loading Event    private void MainForm_Load(object sender, EventArgs e)
    {
        //Calling the method of reading configuration file        ();
        //The form background is set to the picture in the configuration file         = ();
        //Calling the method of reading file directory        ();
        //Read the playlist        sa = new SavingInfo();
        ();
        //Binding LV        BindAllLV();
        BindPlayLV();
        SetLV();
        SetLrcBG();
         = ;
        //Show time         = ();
        //The two lbls are used to display the progress according to the total length of the song and the playback length, and set the position overlapping.         = ;
        //Start the thread        thread = new Thread(Renovate);
         = true;
        ();
      
    }
    #endregion
    #region Backend Refresh    /// <summary>
    /// Refresh time count status, etc.    /// </summary>
    private void Renovate()
    {
      //while (true)
      //{
      // //Count      //  Count();
      // // Get the current time      //   = ();
      // //No song prompt, if the playlist is empty and the current playlist is in the display status      //  if ( == 0 && )
      //     = true;
      //  else
      //     = false;
      //  (1000);
      //}
    }
    #endregion
    #region Set LV background    /// <summary>
    /// Set LV background    /// </summary>
    public void SetLV()
    {
      bm = new Bitmap(, , );
      //Draw a rectangle, define the starting position and width and height      Rectangle r = new Rectangle(, , , );
      //Seave part of bm according to rectangular size and starting position      bm= (r,);
      //Set the captured image as lv background to achieve the effect of perfect fit with the main form background      ();
       = (Image)bm;
      ();
      ();
       = (Image)bm;
      ();
    }
    #endregion
    
    #region Get songs    /// <summary>
    /// Get the song to play    /// </summary>
    private void GetSong()
    {
      //Receive and play song method to obtain a song object       = ();
      //If the song object is not empty      if (mySong != null)
      {
        //The player path is set to the song path         = ;
        //Call the method to display the song name and singer         = ();
         = ();
         = ;//Modify the playback status        //The play button picture is modified to pause picture         = ("Images\\"); 
        try
        {
          
          //Read the lyrics path          ();
          AddLrc();
          //Start a timer, this timer only controls the lyrics carousel          ();
        }
        catch (Exception)
        {
          LrcNull();
          itemLrc = new ListViewItem();
          ("The song lyrics file cannot be found!");
           = ;
           = new Font("Microsoft Yahei", 14.25F, ((FontStyle)(( | ))), , ((byte)(134)));
          (itemLrc);
        }
      }
    }
    #endregion
    #region main timer    //Timer 1    private void timer1_Tick(object sender, EventArgs e)
    {
      if ( == "")
      {
         = false;
        return;
      }
      
      //If there is no song currently playing, call the method to get the song      if ( == null)
      {
        GetSong();
      }
      //The next song is automatically, if the current playback is completed      if ( == )
      {
         = null; // Set the song to empty         = "";
        ();
        PlayModel();
        ();
        (1000);
      }
      // Cut the song, the song is currently played and the playback status is cut      if ( != null &&  == )
      {
         = "";//Empty        ();
        ();
         = "";
         = null;
      }
      //If there is currently a song playing, some attributes that need to be obtained      if (!="")
      {
        //Set the color of the currently played song        SongColor();
        //Get the display value of the volume control and calculate it according to the number of control scales        this. =  / 10;
        //The song time displays, one is the total length, the other is the played length, the string type         = ;
         = ;
        //Progress bar, two lbl controls are used, song length/played length = width of lbl1/width of lbl2        //Multiply 1000 to prevent errors from occurring when the data is too small        double temp = (*1000) / (*1000);
        double width = ;
        double avg = width / temp;
        //Judgement>1 In order to prevent the avg value from being less than the int limit        if(avg>1)
           = Convert.ToInt32(avg);
         = ;
        //The tray displays the playing song        this. = + ;
      }
    }
    #endregion
    #region Play button    /// <summary>
    /// Play button, switch playback or pause    /// </summary>
    private void btnPlay_Click(object sender, EventArgs e)
    {
      if(!)
        ();
      //If it is currently playing      if ( == )
      {
        //Pause playback        ();
        //Modify the button image to play         = ("Images\\");
        //Stop the timer to control lyrics scrolling        if ()
          ();
      }
      else if ( == )
      {
        //Start playback        ();
        //The button image is modified to pause         = ("Images\\");
        //Scroll the lyrics        if (!&&>0)
          ();
      }
    }
    #endregion
    #region Cut song    //Switch the next song and call the song cutting method    private void btnRight_Click(object sender, EventArgs e)
    {
      (false);
    }
    //Previous song, call the song cutting method    private void btnLeft_Click(object sender, EventArgs e)
    {
      (true);
    }
    #endregion
    #region Volume    //Mute, mute!  = Volume is 0    private void btnModel_Click(object sender, EventArgs e)
    {
      //If the player is not muted, the foreground text shows a red cross and the state is changed to mute      if ( == false)
      {
         = "×";
         = true;
      }
      else//On the contrary, it is already silent, clear the red cross and set the non-silent state      {
         = "";
         = false;
      }
    }
    //Set the volume, this event is when the control scale value changes    private void trackBar1_Scroll(object sender, EventArgs e)
    {
      //The volume is set to control scale *10 (because it is /10 when initializing)       = this. * 10;
    }
    #endregion
    #region Song List Operation    /// <summary>
    /// Bind all song LV data    /// </summary>
    private void BindAllLV()
    {
      //If all song collections are empty, end      if ( == null)
        return;
      ();
      //Travel the collection to bind to all songs LV      foreach (Song s in )
      {
        ListViewItem item = new ListViewItem();
         = s;
        ();
        (item);
      }
    }
    //Click to display all songs    private void tslblAll_Click(object sender, EventArgs e)
    {
      //Hide playlist       = false;
      //The two LV positions overlap       = ;
      //Change the background color after clicking       = ;
       = ;
      //Show all songs LV       = true;
    }
    //Click to display the playlist    private void tslblPlay_Click(object sender, EventArgs e)
    {
      //Call bind to play LV data      BindPlayLV();
      //The background color changes       = ;
       = ;
      //Hide all songs LV       = false;
      //Show playback LV       = true;
    }
    /// <summary>
    /// Bind playlist    /// </summary>
    private void BindPlayLV()
    {
      //If the playback collection is not empty      if (!=null)
      {
        ();
        //Travel the collection binding playback LV        foreach (Song s in )
        {
          int id =  + 1;
           = id;
          ListViewItem item = new ListViewItem(());
          ();
           = s;
          (item);
        } 
      }
    }
    /// <summary>
    /// Song count    /// </summary>
    private void Count()
    {
      //if ()
      // = "Selected" + + "\\Total" + ;      //if ()
      // = "total" + ;    }
    #endregion
    #region Lyrics Operation    /// <summary>
    /// Set lyrics background    /// </summary>
    public void SetLrcBG()
    {
      bm = new Bitmap(, , );
      //Draw a rectangle, define the starting position and width and height      Rectangle r = new Rectangle(, , , );
      //Seave part of bm according to rectangular size and starting position      bm = (r, );
      //Set the captured image as lv background to achieve the effect of perfect fit with the main form background      ();
       = (Image)bm;
      ();
    }
    int nullCount;//Record empty line position    /// <summary>
    /// Set empty lines to make the lyrics in the lyrics    /// </summary>
    private void LrcNull()
    {
      ();
      nullCount = (int)(( / 30 / 2));
      for (int i = 0; i <= nullCount; i++)
      {
        ("");
      }
    }
    /// <summary>
    /// Add lyrics    /// </summary>
    private void AddLrc()
    {
      LrcNull();
      foreach (string key in )
      {
        ListViewItem item = new ListViewItem();
        ([key]);
         = key;
        (item);
      }
    }
    //Only control lyrics carousel    private void timer2_Tick(object sender, EventArgs e)
    {
      //Call the method to display lyrics      ShowLrc();
    }
    /// <summary>
    /// Show lyrics    /// </summary>
    private void ShowLrc()
    {
      foreach (ListViewItem item in )
      {
        if ( == null)
          continue;
        if (() ==  )
        {
           = ;
           = new Font("Chinese Amber", 16F, , , ((byte)(134)));
          [ -1].ForeColor = ;
          [ - 1].Font = new Font("Microsoft Yahei", 12F, , , ((byte)(134)));
          if ( + 1<)
            [+1].EnsureVisible();       
        }
      }
    }
    #endregion
    #region form hidden to tray settings    //Minimize to the tray    private void btnMix_Click(object sender, EventArgs e)
    {
      ();
    }
    //When the size state of the main form changes    private void MainForm_SizeChanged(object sender, EventArgs e)
    {
      if ( == )
      {
        //Start a control, which allows the program to display icons in the lower right corner, and you need to set the icon picture displayed by the control in advance.        this. = true;
      }
    }
    //Track display, double-click to display the form    private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
      ShowMain();
    }
    /// <summary>
    /// Show the main form    /// </summary>
    public void ShowMain()
    {
      if (!)
      {
         = true;
        ();
         = false;
      }
      else
      {
         = true;
         = false;
      }
    }
    //The tray opens the form    private void tsmiShow_Click(object sender, EventArgs e)
    {
      ShowMain();
    }
    //The tray exits    private void tsmiExit_Click(object sender, EventArgs e)
    {
      ();
    }
    #endregion
    #region Form displacement    Point mouseOff;//Mouse Move Position Variable    bool leftFlag;//Whether the mark is left-click    private void pnlMain_MouseDown(object sender, MouseEventArgs e)
    {
      if ( == )
      {
        mouseOff = new Point(-, -); //Get the value of the variable        leftFlag = true; // When clicking the left button, mark it as true;      }
    }
    private void pnlMain_MouseMove(object sender, MouseEventArgs e)
    {
      if (leftFlag)
      {
        Point mouseSet = ;
        (, ); //Set the position after moving        Location = mouseSet;
      }
    }
    private void pnlMain_MouseUp(object sender, MouseEventArgs e)
    {
      if (leftFlag)
      {
        leftFlag = false;//Authenticate as false after releasing the mouse;      }
    }
  #endregion
    #region Progress bar scrolling block movement    int runX;//Record the initial position of the scroll block    private void picRun_MouseDown(object sender, MouseEventArgs e)
    {
      runX = ;
    }
    //Release the mouse displacement and progress    private void picRun_MouseUp(object sender, MouseEventArgs e)
    {
       +=  - runX -  / 2;
      if ( > )
         = ;
      if(<)
         = ;
      if (mySong != null)
      {
         = - ;
        double temp = (*1000.0 )/ (*1000.0);
         =  / temp;
      }
    }
    #endregion
    #region song addition and deletion operation    //Add songs to playlist    private void tsmiAdd_Click(object sender, EventArgs e)
    {
      if ( > 0)
      {
        foreach (ListViewItem item in )
        {
           // traverse the playback collection, if it exists, do not add it           foreach (Song s in )
           {
             if ( == )
             {
               (s);
               break;
             }
           }
           ( as Song);
        }
      }
    }
    //All songs: Delete selected songs    private void tsmiDel_Click(object sender, EventArgs e)
    {
      foreach (ListViewItem item in )
      {
        if ()
        {
          ( as Song);
        } 
      }
      BindAllLV();
    }
    //Select all songs    private void tsmiCheck_Click(object sender, EventArgs e)
    {
      foreach (ListViewItem item in )
      {
        if ( == "Select All")
        {
           = true;
          if(+1==)
             = "Uncheck";
        }
        else
        {
           = false;
          if ( + 1 == )
             = "Select All";
        }
      }
    }
    //Select the check box while selecting the item    private void lvSong_MouseDown(object sender, MouseEventArgs e)
    {
      if ( > 0 &&  == )
      {
        [0].Checked = true;
      }
    }
    //Playlist deletion event    private void tsmiPlayDel_Click(object sender, EventArgs e)
    {
      foreach (ListViewItem item in )
      {
        if ()
        {
          // = ([+1].Tag as Song).Id;
          // = null;
          ( as Song);
        }
      }
      BindPlayLV();
    }
    //Clear the playlist    private void tsmiPlayClear_Click(object sender, EventArgs e)
    {
      ();
       = null;
      BindPlayLV();
    }
    //Delete file from playlist    private void tsmiPlayDelFile_Click(object sender, EventArgs e)
    {
      if ( > 0)
      {
        DelFile([0]);
      }
    }
    /// <summary>
    /// Delete a corresponding file    /// </summary>
    /// <param name="item"></param>
    private void DelFile(ListViewItem item)
    {
      try
      {
        string path = ( as Song).FileName;
        (path);
        BindAllLV();
        BindPlayLV();
      }
      catch (Exception)
      {
        ("This file is read-only or the user permissions are insufficient and cannot be deleted!");
      }
    }
    //Delete files from all songs    private void tsmiDelFile_Click(object sender, EventArgs e)
    {
      if ( > 0)
      {
        DelFile([0]);
      }
    }
    //Double-click on the list item to play the song    private void lvPlay_DoubleClick(object sender, EventArgs e)
    {
      if (!)
      {
         = ([0].Tag as Song).Id;
        ();
      }
      if ( > 0)
      {
         = ([0].Tag as Song).Id;
         = null;
      }
    }
    #endregion
    #region Settings    //Jump Settings Form    private void btnSet_Click(object sender, EventArgs e)
    {
      SetForm set = new SetForm();
       = this;//Transfer the main form over      (this);
    }
    #endregion
    #region Rollback    /// <summary>
    /// After the path is reset    /// </summary>
    public void Back()
    {
      BindAllLV();
      ();
      ();
    }
    #endregion
    #region Exit    //Save the list when closed    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
      if ()
        ();
    }
    //Panel Exit    private void btnExit_Click(object sender, EventArgs e)
    {
      if ()
      {
        ();
      }
      else
      {
        ();
      }
    }
 
    #endregion
    #region background color and other transformation control    private void btnLeft_MouseEnter(object sender, EventArgs e)
    {
      ((Button)sender).BackgroundImage = ("Images//allbtn_highlight.png");
    }
    private void btnLeft_MouseLeave(object sender, EventArgs e)
    {
      ((Button)sender).BackgroundImage = null;
    }
    private void tslblPlay_MouseEnter(object sender, EventArgs e)
    {
      ((ToolStripLabel)sender).BackgroundImage = ("Images//Album_bkg_wubian.png");
    }
    private void tslblPlay_MouseLeave(object sender, EventArgs e)
    {
      ((ToolStripLabel)sender).BackgroundImage = null;
    }
    //Select to change color    private void lvSong_ItemChecked(object sender, ItemCheckedEventArgs e)
    {
      foreach (ListViewItem item in )
      {
        if ()
        {
           = ;
        }
        else
        {
           = ;
        }
      }
    }
    /// <summary>
    /// Change the color of the currently playing song    /// </summary>
    private void SongColor()
    {
      foreach (ListViewItem item in )
      {
        if ([1].Text == )
        {
           = ;
        }
        else
        {
           = ;
        }
      }
    }
    #endregion
    #region Select lyrics    private void lvLrc_MouseDown(object sender, MouseEventArgs e)
    {
      if (>0&&[0] == itemLrc)
      {
        if (())
        {
          AddLrc();
          //Start a timer, this timer only controls the lyrics carousel          ();
        }
      }
    }
    #endregion
    #region Form Maximization Settings    Size now;//Original size    Point pN;//Original location    //maximize    private void btnMax_Click(object sender, EventArgs e)
    {
      Size max = new Size( - 10,  - 20);
      if ( != max)
      {
        pN = ;
        now= ;
         = max;
         = 5;
         = 5;
         = ("Images//")
;
      }
      else
      {
         = pN;
         = now;
         = ("Images//");
      }
      SetLV();
      SetLrcBG();
    }
    #endregion
    #region lyrics, MV switching    private void tsmiLrc_Click(object sender, EventArgs e)
    {
       = true;
       = false;
       = ;
       = ;
    }
    private void tsmiMv_Click(object sender, EventArgs e)
    {
       = ;
       = ;
       = false;
       = true;
       = ;
       = ;
    }
    #endregion
    #region Playback mode switch    /// <summary>
    /// Playback mode    /// </summary>
    private void PlayModel()
    {
      if ()
      {
        ();
      }
      else if ()
      {
        ();
      }
    }
    private void tsmiXH_Click(object sender, EventArgs e)
    {
      ToolStripMenuItem ts=((ToolStripMenuItem)sender);
      foreach(ToolStripMenuItem item in )
      {
        if ( && ts == item)
        {
          continue;
        }
        else
        {
           = false;
        }
      }
    }
    #endregion
    
  }
}

I hope that the examples described in this article can have a certain reference value for everyone's C# program development.