Window Media PLayer in C# - c#

i'm building a Music PLayer and so i choose to use the library of Window Media Player:
Now i got stuck 'cos i wish show the song's name in a listBox and change songs in real time but i don't know how go on.
I store songs from a Folder and so when the Music Player run the songs from the Url choose.
I show you a code snippet :
private void PlaylistMidday(String folder, string extendsion)
{
string myPlaylist = "D:\\Music\\The_Chemical_Brothers-Do_It_Again-(US_CDM)-2007-SAW\\";
ListView musicList = new ListView();
WMPLib.IWMPPlaylist pl;
WMPLib.IWMPPlaylistArray plItems;
plItems = player1.playlistCollection.getByName(myPlaylist);
if (plItems.count == 0)
pl = player1.playlistCollection.newPlaylist(myPlaylist);
else
pl = plItems.Item(0);
DirectoryInfo dir = new DirectoryInfo(folder);
FileInfo[] files = dir.GetFiles(extendsion, SearchOption.AllDirectories);
foreach (FileInfo file in files)
{
string musicFile01 = file.FullName;
string mName = file.Name;
ListViewItem item = new ListViewItem(mName);
musicList.Items.Add(item);
WMPLib.IWMPMedia m1 = player1.newMedia(musicFile01);
pl.appendItem(m1);
}
player1.currentPlaylist = pl;
player1.Ctlcontrols.play();
}
On Load i decide to play the songs of "myPLaylist" so i ask you do you know some way how to show the songs of my playlist in a listbox and when i click on the selected item i will change songs?
Thansk for your support.
Nice Regards

Instead of adding songs to playlist, you can add them to a List<string> as a return value. On load event, you just call the method that get list of media file paths in the folder, and then add them into a listbox.
To change the song being played, you just need to add SelectedValueChanged/SelectedItemChanged event, and in this event, get the file path that is currently selected in the listbox, then have WMP played it for you :)
private void Form1_Load(object sender, EventArgs e)
{
List<string> str = GetListOfFiles(#"D:\Music\Bee Gees - Their Greatest Hits - The Record");
listBox1.DataSource = str;
listBox1.DisplayMember = "str";
}
private List<string> GetListOfFiles(string Folder)
{
DirectoryInfo dir = new DirectoryInfo(Folder);
FileInfo[] files = dir.GetFiles("*.mp3", SearchOption.AllDirectories);
List<string> str = new List<string>();
foreach (FileInfo file in files)
{
str.Add(file.FullName);
}
return str;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string strSelected = listBox1.SelectedValue.ToString();
MessageBox.Show(strSelected); //Just demo, you can add code that have WMP played this file here
}
a quick solution. :). Not very good, but it works. Help this hope

Related

How to make difference between FileInfo and DirectoryInfo in a file explorer in list view

I would like to make a file explorer with Windows Forms, i already have done a few things, but when i would like to use the DoubleClick event of my ListView I dont know how to code that file explorer needs to act differently when I make the doubleclick on a file or a folder.
My goal is:
Clicking on a file - Loads its text into a TextBox
Clicking on a directory - Opens it and loads it into the listview.
I know how to do 1. and 2. as well, I just don't know how can I make my DoubleClick function know what the selected item in ListView was 1. or 2.
I build my ListView like this:
private void miOpen_Click(object sender, EventArgs e)
{
InputDialog dlg = new InputDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
DirectoryInfo parentDI = new DirectoryInfo(dlg.Path);
listView1.Items.Clear();
try
{
foreach (DirectoryInfo df in parentDI.GetDirectories())
{
ListViewItem lvi = new ListViewItem(new string[] {
df.Name, df.Parent.ToString(),
df.CreationTime.ToShortDateString(), df.FullName });
listView1.Items.Add(lvi);
}
foreach (FileInfo fi in parentDI.GetFiles())
{
ListViewItem lvi = new ListViewItem(new string[] {
fi.Name, fi.Length.ToString(),
fi.CreationTime.ToShortDateString(), fi.FullName } );
listView1.Items.Add(lvi);
}
}
catch { }
}
}
Add the DirectoryInfo or the FileInfo objects to the Tag property of the ListViewItem. I.e
...
var lvi = new ListViewItem(new string[] {
df.Name,
df.Parent.ToString(),
df.CreationTime.ToShortDateString(),
df.FullName
});
lvi.Tag = df;
listView1.Items.Add(lvi);
...
or for the file info:
lvi.Tag = fi;
Then, after having selected an item in the listview:
private void btnTest_Click(object sender, EventArgs e)
{
// Show the first item selected as an example.
if (listView1.SelectedItems.Count > 0) {
switch (listView1.SelectedItems[0].Tag) {
case DirectoryInfo di:
MessageBox.Show($"Directory = {di.Name}");
break;
case FileInfo fi:
MessageBox.Show($"File = {fi.Name}");
break;
default:
break;
}
}
}
Try this code:
FileAttributes fileAttributes = File.GetAttributes("C:\\file.txt");
if (fileAttributes.HasFlag(FileAttributes.Directory))
Console.WriteLine("This path is for directory");
else
Console.WriteLine("This path is for file");

Invoking a combobox's selected folder(C#)

I am using two comboboxes, in which 1st box will display folders in the specified location from that drop down list i will be selecting the necessary folder, so after selection the second combobox should list only the files depending on the 1st box's selected folder.(NOTE:Am not working with database, just accessing computers folder). Am working with visual studio 2013 in C#. Thanks in advance.
DirectoryInfo di = new DirectoryInfo(#"C:\Users\jeeva\Desktop\1234");
DirectoryInfo[] folders = di.GetDirectories();
comboBox1.DataSource = folders;
string selected =comboBox1.SelectedItem.ToString();
String fullpath = Path.Combine(#"C:\Users\jeeva\Desktop\1234", selected);
DirectoryInfo di1 = new DirectoryInfo(fullpath);
DirectoryInfo[] folders1 = di1.GetDirectories();
comboBox2.DataSource = folders1
It is done basically in 2 steps. You just need to separate them in your code.
1) get the folders into your combobox (may be already in the constructor of the Form):
DirectoryInfo di = new DirectoryInfo(#"C:\Users\jeeva\Desktop\1234");
DirectoryInfo[] folders = di.GetDirectories();
comboBox1.DataSource = folders;
2) double click comboBox1 in the designer. This will create an event which is triggered when the user selects an item. Inside it you can then get all the subfolders and give them as DataSource to the ComboBox which shall display them.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected =comboBox1.SelectedItem.ToString();
String fullpath = Path.Combine(#"C:\Users\jeeva\Desktop\1234", selected);
DirectoryInfo di1 = new DirectoryInfo(fullpath);
DirectoryInfo[] folders1 = di1.GetDirectories();
comboBox2.DataSource = folders1
}
You can use Directory.GetFiles("folderName") method to populate your second combobox. Directory class resides in System.IO namespace.
You can get the folder list by something like this:
DirectoryInfo obj = new DirectoryInfo("E:\\");//you can set your directory path here
DirectoryInfo[] folders = obj.GetDirectories();
YourDirCombo.DataSource = folders ;
You probably have a method listening to your first combo changes:
private void YourDirCombo_SelectedIndexChanged(object sender, EventArgs e)
now in this you can get the files of the selected folder:
string [] fileEntries = Directory.GetFiles(YourDirCombo.SelectedValue);
YourFileCombo.DataSource = fileEntries;
The following can be optimized and generalized in several different ways - I'm doing it "long hand" to give you the most information possible.
private void initializeComboBoxes()
{
ComboBox c = new ComboBox();
c.Name = "cbx_One";
c.Items.Add("Select a File");
foreach(string direc in System.IO.Directory.GetDirectories(#"PathToYourFiles"))
{
c.Items.Add(direc);
}
c.SelectedIndex = 0;
c.SelectedIndexChanged += loadComboBox2;
Controls.Add(c);
ComboBox c1 = new ComboBox();
c1.Name = "cbx_Two";
c1.Items.Add("Waiting for file selection");
c1.SelectedIndex = 0;
c1.SelectedIndexChanged += loadFile;
Controls.Add(c1);
areComboBoxesUpdating = false;
}
bool areComboBoxesUpdating = true;
protected void loadComboBox2(object sender, EventArgs e)
{
if (!areComboBoxesUpdating)
{
ComboBox c1 = sender as ComboBox;
ComboBox c2 = Controls.Find("cbx_Two", true)[0] as ComboBox;
c2.Items.Clear();
if (c1.SelectedIndex == 0)
{
c2.Items.Add("Waiting for file selection");
}
else
{
c2.Items.Add("Please select a file");
//assuming c1 is the list of directories
foreach (string file in System.IO.Directory.GetFiles(c1.SelectedItem.ToString()))
{
c2.Items.Add(Path.GetFileName(c1.SelectedItem.ToString()));
}
}
areComboBoxesUpdating = true;
c2.SelectedIndex = 0;
areComboBoxesUpdating = false;
}
}
protected void loadFile(object sender, EventArgs e)
{
//a selection has been made from the second box - you have directory in box1 and filename in box2
ComboBox c = sender as ComboBox;
if (c.SelectedIndex > 0)
{
string directory = ((ComboBox)Controls.Find("cbx_One", true)[0]).SelectedItem.ToString();
string file = c.SelectedItem.ToString();
//do something
}
}
On the Onchange event of Combobox1:
ComboBox2.dataSource = System.IO.Directory.GetFiles(ComboBox1.SelectedText)
This should populate all the files in Combobox2

Open image from listbox file name C# winform

I have been working on this in my spare time, to no avail. I really could use a hand getting this to work.
I have a winform in C#. I am currently working with a listbox and a picturebox to display embedded image resources. I want to populate the listbox with just the file name, as the full path is longer than the width of the listbox can accommodate on my form.
Here is some code I was working with:
string[] x = System.IO.Directory.GetFiles(#"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\", "*.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
foreach (string f in x)
{
string entry1 = Path.GetFullPath(f);
string entry = Path.GetFileNameWithoutExtension(f);
listBox1.DisplayMember = entry;
listBox1.ValueMember = entry1;
listBox1.Items.Add(entry);
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation = listBox1.SelectedItem.ToString();
}
If I populate the listbox with the full path,(entry1), things work pretty smooth other than not being able to see the image name you will be selecting due to the length of the full path.
When I try to populate the listbox with (entry), just the file names appear in the listbox, which is desireable, however, the image will no longer open on selection from the listbox.
How can I get this working correctly? Help is greatly appreciated.
Patrick
You're on the right track by setting the DisplayMember and ValueMember properties, but you'd need to make a few corrections, and it might not be necessary here.
Store the original directory path in a separate variable, then just combine that with the file name in your SelectedIndexChanged event to get the original file path.
string basePath =
#"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\";
string[] x = Directory.GetFiles(basePath, "*.jpg");
foreach (string f in x)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(f));
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation =
Path.Combine(basePath, listBox1.SelectedItem.ToString()) + ".jpg";
}
Grant answer is perfectly ok for a simple task like this, but i'll explain another way that may be useful in other situations.
You can define a class to store your filenames and paths, something like:
class images
{
public string filename { get; set; }
public string fullpath { get; set; }
}
This way, your code could be like:
string[] x = System.IO.Directory.GetFiles(#"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\", "*.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
List<images> imagelist=new List<images>();
foreach (string f in x)
{
images img= new images();
img.fullpath = Path.GetFullPath(f);
img.filename = Path.GetFileNameWithoutExtension(f);
imagelist.Add(img);
}
listBox1.DisplayMember = "filename";
listBox1.ValueMember = "fullpath";
listBox1.DataSource = imagelist;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation = ((images)listBox1.SelectedItem).fullpath;
}
I have not tested it,maybe it has any typo, but i hope you get the idea.

How to open file that is shown in listbox?

I have added all startup programs to a listbox.
How can I open the file when I select the item and click on a button?
Listbox code:
private void readfiles()
{
string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
var files = Directory.GetFiles(startfolder).Where(name => !name.EndsWith(".ini"));
foreach (string file in files)
{
startupinfo.Items.Add(System.IO.Path.GetFileName(file));
}
}
I don't know what file type you're trying to open, but this is how you can get the selected item.
Dictionary<string, string> startupinfoDict = new Dictionary<string, string>();
private void readfiles()
{
string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
var files = Directory.GetFiles(startfolder).Where(name => !name.EndsWith(".ini"));
foreach (string file in files)
{
startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));
startupinfoDict.Add(Path.GetFileNameWithoutExtension(file), file);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
string s = listBox1.SelectedItem.ToString();
if (startupinfoDict.ContainsKey(s))
{
Process.Start(startupinfoDict[s]);
}
}
}
Get the currently selected list box item and assuming an application is coupled to the file('s extension use):
Process.Start(fileName);
You can get the selected item by using the SelectedValue property of the listbox.
You can open a file by using Process.Start.
You would initiate a new process declaring the path to the file to execute / open in your button click handler:
Process.Start(#" <path to file> ");
If the selected value in the list box is the file path then:
Process.Start(<name of list box>.SelectedValue);
EDIT:
Change your foreach loop as follows:
foreach (string file in files)
{
startupinfo.Items.Add(System.IO.Path.GetFullPath(file) + #"\" + System.IO.Path.GetFileName(file));
}

How to add multiple files to a playlist

I have one OpenFileDialog control that has Multiselect = true. Now I want to add each file to windows media player playlist but I have no idea how to do that and there is no good example on the internet.
if (ofdSong.ShowDialog() == DialogResult.OK)
{
foreach (string file in ofdSong.FileNames)
{
//Code to add file to the playlist
}
}
With help of DJ KRAZE that gave me the example link and JayJay who wrote that example, here is the solution.
WMPLib.IWMPPlaylist playlist = wmp.playlistCollection.newPlaylist("myplaylist");
WMPLib.IWMPMedia media;
if (ofdSong.ShowDialog() == DialogResult.OK)
{
foreach (string file in ofdSong.FileNames)
{
media = wmp.newMedia(file);
playlist.appendItem(media);
}
}
wmp.currentPlaylist = playlist;
wmp.Ctlcontrols.play();
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
var myPlayList = axWindowsMediaPlayer1.playlistCollection.newPlaylist("MyPlayList");
OpenFileDialog open = new OpenFileDialog();
open.Multiselect =true;
open.Filter = "All Files|*.*";
if(open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
foreach(string file in open.FileNames)
{
var mediaItem = axWindowsMediaPlayer1.newMedia(file);
myPlayList.appendItem(mediaItem);
}
}
axWindowsMediaPlayer1.currentPlaylist = myPlayList;
}
to play multiple items: copy and paste and enjoy

Categories

Resources