AxWMPLib.AxWindowsMediaPlayer autoplay after end of song [duplicate] - c#

This question already has an answer here:
Function call only works when MessageBox.Show() is included?
(1 answer)
Closed 8 years ago.
I try to make simple audio player,
then I try it.
After end of song, the player stopped.
I want to set it automatically and select randomized, at the playlist.
I use URL and a ListBox as playlist..
This is the code snippet at autoplay part:
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (e.newState == 8)
{
Random rnd = new Random();
int nowPlayIndex = rnd.Next(listURLPlayers.Count);
axWindowsMediaPlayer1.URL = listURLPlayers[nowPlayIndex];
axWindowsMediaPlayer1.Ctlenabled = true;
axWindowsMediaPlayer1.Ctlcontrols.play();
listAudio.SelectedIndex = nowPlayIndex;
}
}
But I try it then the URL changed, but not played automatically.
What is wrong with my code?
https://github.com/mudzakkir/MP3Player.git
Please help.

Ok it is now working..
I should use Timer..
My code is now like this:
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 Mp3Player
{
public partial class MediaPlayer : Form
{
string HomeDir;
string[] sPlaylists, sURLs;
List<string> listURLPlayers = new List<string>();
public MediaPlayer()
{
InitializeComponent();
HomeDir = Directory.GetCurrentDirectory();
string[] playlist = File.ReadAllLines("playlist.txt");
foreach (string fileText in playlist)
{
listAudio.Items.Add(fileText);
}
string[] playlistUrl = File.ReadAllLines("playlistURL.txt");
foreach (string fileText in playlistUrl)
{
listURLPlayers.Add(fileText);
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
sPlaylists = openFileDialog1.SafeFileNames;
sURLs = openFileDialog1.FileNames;
for (int i = 0; i < sPlaylists.Length; i++)
{
listAudio.Items.Add(sPlaylists[i]);
}
for (int i = 0; i < sURLs.Length; i++)
{
listURLPlayers.Add(sURLs[i]);
}
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter("playlist.txt");
foreach (var item in listAudio.Items)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
SaveFile = new System.IO.StreamWriter("playlistURL.txt");
foreach (var item in listURLPlayers)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
}
}
private void listAudio_MouseDoubleClick(object sender, MouseEventArgs e)
{
axWindowsMediaPlayer1.URL = listURLPlayers[listAudio.SelectedIndex];
}
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (e.newState == 8)
{
timer1.Enabled = true;
}
}
private void listAudio_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = listURLPlayers[listAudio.SelectedIndex];
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
Random rnd = new Random();
int nowPlayIndex = rnd.Next(listURLPlayers.Count);
axWindowsMediaPlayer1.URL = listURLPlayers[nowPlayIndex];
listAudio.SelectedIndex = nowPlayIndex;
}
}
}
Thank You

Related

C# DataGridView stuck in button1_Click event?

I am trying to get the cell value in a string from the selected cell in the "Document Number" column in a DataGridView. My code to retrieve data from SharePoint and populate the DataGridView works fine, but I seem to be caught in a loop there? I cannot execute any other methods after populating the DataGridView . I can select a new search term and execute the Button1_Click event again successfully, but I cannot get any other methods to execute?
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 Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace BuyersForeverFriend
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string userSearch = textBox1.Text;
button1.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
using (ClientContext ctx = new ClientContext("https://teamsites.nafta.fcagroup.com/sites/PSOAPPS/iws/"))
{
var userInput = textBox1.Text;
Web web = ctx.Web;
List list = web.Lists.GetById(new Guid("61ef6657-eff7-42cb-99e1-8afd590334ec"));
var q = new CamlQuery() { ViewXml = "<View><Query><Where><Contains><FieldRef Name='Item_x0020_Description' /><Value Type='Note'>" + userInput + "</Value></Contains></Where></Query><ViewFields><FieldRef Name='Title' /><FieldRef Name='Topic_x002d_' /><FieldRef Name='Item_x0020_Description' /></ViewFields><QueryOptions /></View>" };
var r = list.GetItems(q);
ctx.Load(r);
ctx.ExecuteQuery();
if (r.Count != 0)
{
var searchResults = new DataTable();
searchResults.Columns.AddRange(new[]
{
new DataColumn("ID"), new DataColumn("Document Number"), new DataColumn("Item Description"), new DataColumn("Topic")});
foreach (var oListItem in r)
{
searchResults.Rows.Add(oListItem["ID"], oListItem["Title"], oListItem["Item_x0020_Description"],
oListItem["Topic_x002d_"]);
}
if (dataGridView1 != null)
{
dataGridView1.DataSource = searchResults;
dataGridView1.Refresh();
dataGridView1.Columns[2].DefaultCellStyle.Format = "dd'/'MM'/'yyyy";
var dataGridViewColumn = dataGridView1.Columns["ID"];
if (dataGridViewColumn != null)
dataGridViewColumn.Visible = false;
}
else
MessageBox.Show("after else statement");
}
}
MessageBox.Show("after sharepoint if statement");
return;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("a cell was clicked");
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
MessageBox.Show("starting routine");
if (dataGridView1.SelectedCells.Count > 0)
{
int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
string a = Convert.ToString(selectedRow.Cells["Document Number"].Value);
MessageBox.Show(a);
textBox2.Text = ("The var =" + a);
}
else MessageBox.Show("if did not end up true");
}
}
}
I failed to initialize these, after adding them to the form method...poof everything works! :
public Form1()
{
InitializeComponent();
dataGridView1.CellClick += dataGridView1_CellClick;
dataGridView1.SelectionChanged += dataGridView1_SelectionChanged;
}

Winforms - Listbox will not update contenets until clicked

I'll try to add as much information as needed, please tell me if you need any extra info that I haven't added and I'll do my best to provide it.
The basics of my problem is that whenenver I press a button, it will grab the file I select and save it to a text file. This works fine and I can save as many files as needed. The problem lies in the listbox of my listbox. My app is a soundboard, and I want filenames with their hotkeys to be displayed on the listbox which almost works fine. On loading the application the listbox will take all saved files and display them accordingly once and on adding a file, the file will be added to the listbox and it will be saved. As I said this almost works because for some reason unknown to me, you have to click the listbox for it to add the content. My code is as follows:
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
songToAdd = filePath;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
add = true;
}
}
public bool add = false;
public string songToAdd;
public bool load = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (load == true)
{
listBox1.DataSource = File.ReadAllLines(#"Sounds.txt");
load = false;
}
if(add == true)
{
listBox1.Items.Add(songToAdd);
add = false;
}
}
}
P.S. I'm still a novice at windows forms and this app is still nowhere near done.
Instead of adding the items in SelectedIndexChanged I added them in outside. I load the saved songs in Form1_Load and I open/save the loaded files in the addFile() function.
Edited Code:
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;
using System.Media;
using System.Security.Cryptography.X509Certificates;
using System.Runtime;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using System.Diagnostics;
namespace SoundBoard
{
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public bool load = true;
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
listBox1.Items.Add(filePath);
}
}
public bool loada = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
if (loada == true)
{
listBox1.Items.Add(File.ReadAllLines(#"Sounds.txt"));
loada = false;
}
}
}
}

axWindowsMediaPlayer Crashes Program

I am trying to make a MP3 player with playlist functionality, I have googled everywhere, tried examples, but nothing works. Where the code freezes up at is when p[ListBox1.SelectedIndex + 1]; is called, and I have no idea why it locks up the program. I have tried making an array and selecting the next song through that, but that also didn't work.
I think this is the easiest way to do this. But it locks up the program for some reason.
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.Threading;
using System.Collections;
namespace MusicPlayer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] f, p;
ArrayList playlist = new ArrayList();
private int current_index = 0;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if(openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK){
f = openFileDialog1.SafeFileNames;
p = openFileDialog1.FileNames;
for (int i = 0; i < f.Length; i++)
{
listBox1.Items.Add(f[i]);
}
foreach (string d in open.FileNames)
{
listBox1.Items.Add(d);
}
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
axWindowsMediaPlayer1.URL = p[listBox1.SelectedIndex];
}
private void Form1_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.PlayStateChange += new AxWMPLib._WMPOCXEvents_PlayStateChangeEventHandler(MediaPlayer_PlayStateChange);
}
public void MediaPlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
switch (axWindowsMediaPlayer1.playState)
{
// Locks up here
case WMPLib.WMPPlayState.wmppsReady:
axWindowsMediaPlayer1.URL = p[listBox1.SelectedIndex + 1];
break;
case WMPLib.WMPPlayState.wmppsStopped:
axWindowsMediaPlayer1.URL = p[listBox1.SelectedIndex + 1];
break;
default:
break;
}
}
}
}
EDIT:
I updated my code and this is what it looks like:
public void MediaPlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
switch (axWindowsMediaPlayer1.playState)
{
case WMPLib.WMPPlayState.wmppsReady:
axWindowsMediaPlayer1.BeginInvoke(new Action(change_song));
break;
case WMPLib.WMPPlayState.wmppsStopped:
axWindowsMediaPlayer1.BeginInvoke(new Action(change_song));
break;
default:
break;
}
}
void change_song()
{
axWindowsMediaPlayer1.URL = p[listBox1.SelectedIndex + 1];
}
But when I run this, it gets stuck at "Media Changing" and eventually does nothing.

Removing listbox item

Im at beginner level and have tried for a while now. Im trying to remove an item from a ListBox with the help of a remove button. The code is not giving away any errors but the items is not disappearing from the list.
This is the part im struggling with
void taBort()
{
listboxKontakter.SelectedItems.Remove(listboxKontakter.SelectedItems);
textboxAnteckningar.Clear();
textboxGatuadress.Clear();
textboxNamn.Clear();
textboxPostnummerOrt.Clear();
textboxEmail.Clear();
textboxFödelsedag.Value = DateTime.Now;
}
Here is my entire code:
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 adressboken
{
public partial class Form1 : Form
{
List<Kontakter> kontaktLista = new List<Kontakter>();
Kontakter person;
string path = "kontakter.txt";
public Form1()
{
InitializeComponent();
}
private void LäggTill_Click(object sender, EventArgs e)
{
person = new Kontakter();
person.FullständigtNamn = textboxNamn.Text;
person.Gatuadress = textboxGatuadress.Text;
person.PostnummerOrt = textboxPostnummerOrt.Text;
person.Födelsedag = textboxFödelsedag.Value;
person.Email = textboxEmail.Text;
person.Anteckningar = textboxAnteckningar.Text;
kontaktLista.Add(person);
listboxKontakter.DataSource = null;
listboxKontakter.DisplayMember = "FullständigtNamn";
listboxKontakter.DataSource = kontaktLista;
textboxAnteckningar.Clear();
textboxGatuadress.Clear();
textboxNamn.Clear();
textboxPostnummerOrt.Clear();
textboxEmail.Clear();
textboxFödelsedag.Value = DateTime.Now;
textboxAntal.Text = kontaktLista.Count.ToString();
}
private void Rensa_Click(object sender, EventArgs e)
{
textboxAnteckningar.Clear();
textboxGatuadress.Clear();
textboxNamn.Clear();
textboxPostnummerOrt.Clear();
textboxEmail.Clear();
textboxFödelsedag.Value = DateTime.Now;
}
void taBort()
{
textboxAnteckningar.Clear();
textboxGatuadress.Clear();
textboxNamn.Clear();
textboxPostnummerOrt.Clear();
textboxEmail.Clear();
textboxFödelsedag.Value = DateTime.Now;
}
private void Form1_Load(object sender, EventArgs e)
{
kontaktLista = new List<Kontakter>();
string line = "";
StreamReader sr = new StreamReader(path);
while ((line = sr.ReadLine()) != null)
{
string[] listarray = line.Split(',');
person = new Kontakter();
person.FullständigtNamn = listarray[0];
person.Gatuadress = listarray[1];
person.PostnummerOrt = listarray[2];
person.Email = listarray[3];
person.Födelsedag = Convert.ToDateTime(listarray[4]);
person.Anteckningar = listarray[5];
kontaktLista.Add(person);
}
sr.Close();
listboxKontakter.DataSource = kontaktLista;
listboxKontakter.DisplayMember = "FullständigtNamn";
}
public void listboxKontakter_Click(object sender, EventArgs e)
{
person = (Kontakter)listboxKontakter.SelectedItem;
textboxNamn.Text = person.FullständigtNamn;
textboxGatuadress.Text = person.Gatuadress;
textboxPostnummerOrt.Text = person.PostnummerOrt;
textboxEmail.Text = person.Email;
textboxFödelsedag.Value = person.Födelsedag;
var selectedindex = listboxKontakter.SelectedItems;
}
private void Spara_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(path);
foreach (Kontakter k in kontaktLista)
{
sw.WriteLine(k.FullInfo);
}
sw.Close();
}
private void taBortToolStripMenuItem_Click(object sender, EventArgs e)
{
taBort();
}
private void TaBort_Click(object sender, EventArgs e)
{
taBort();
}
}
}
Your code seems to remove all selected items, and does not refresh.
How about:
listboxKontakter.SelectedItems.Remove(listboxKontakter.SelectedItem);
listboxKontakter.Refresh();
You remove only the single selected item, then refresh your listbox.
If you want to remove ALL items try:
listboxKontakter.Items.Clear();
If you use a DataSource try:
listboxKontakter.DataSource = null;
If all else fails you could loop through the collection and RemoveAt:
for(int i=listboxKontakter.Items.Count; i > -1; i--) {
{
listboxKontakter.Items.RemoveAt(i);
}
Based on a bit of chatting, this should work for you:
void taBort()
{
var newList = (List<Kontakter>)listboxKontakter.DataSource;
var ds = newList.Where(k => k.FullständigtNamn != ((Kontakter)listboxKontakter.SelectedItem).FullständigtNamn).ToList();
listboxKontakter.DataSource = ds;
listboxKontakter.DisplayMember = "FullständigtNamn";
textboxAnteckningar.Clear();
textboxGatuadress.Clear();
textboxNamn.Clear();
textboxPostnummerOrt.Clear();
textboxEmail.Clear();
textboxFödelsedag.Value = DateTime.Now;
}
If you want to remove several items at once try:
var ds = newList.Where(k => !listboxKontakter.SelectedItems.Contains(k.FullständigtNamn)).ToList();
How about:
listboxKontakter.Items.Remove(itemthatneedstoberemoved)
and
listboxKontakter.Items.Clear();
(I assume you called the listbox, listboxKontakter?)
:
Take a look at this
.SelectedItems is basically just an array list of what items you have selected, so you will need to access those like this .SelectedItems[0] .SelectedItems[1].
However the above code even with the [0], [1] will only remove them from the selected list not the actual list box.
If you want to remove them from the list box you need to use the .Items.Remove call.
while(listboxKontakter.SelectedItems.Count >0)
{
listboxKontakter.Items.Remove(listboxKontakter.SelectedItems[0]);
}
EDIT:
If it is a single select listbox all you have to do is
listboxKontakter.Items.Remove(listboxKontakter.SelectedItem);

Working with C# Proxy List

I'm trying to build an application that goes to a certain website (from a textbox) x number of times (also from a textbox) through a proxy. What I'm having trouble with is getting the proxy list into the program and using it in the webBrowser control. Here's what I have so far. Any help is appreciated. Thanks.
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 System.Security.Permissions;
using Microsoft.Win32;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Net;
namespace LetsBot
{
public partial class TrafficBot : Form
{
public TrafficBot()
{
InitializeComponent();
}
private void btnClear_Click(object sender, EventArgs e)
{
this.txtURL.Clear();
this.txtProxy.Clear();
this.txtURL.Focus();
}
private void btnStart_Click(object sender, EventArgs e)
{
this.lblBrowsing.Show();
this.btnStart.Enabled = false;
int n = Convert.ToInt32(this.txtNumVisits.Text);
for (int i = 0; i < n; i++)
{
string url = this.txtURL.Text;
this.webBotBrowser.Navigate(url);
while (webBotBrowser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
string PageText = this.webBotBrowser.DocumentText.ToString();
Thread.Sleep(5000);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
this.btnStart.Enabled = true;
this.webBotBrowser.Stop();
this.txtURL.Focus();
}
private void btnExit_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Exit Traffic Bot?", "Don't Let Me Go!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
Application.Exit();
}
else if (dialogResult == DialogResult.No)
{
}
}
private void webBotBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
if (e.CurrentProgress > 0)
{
ProgressBar.Value = (int)(e.CurrentProgress / e.MaximumProgress * 100);
}
}
private List<string> getProxyListFromText(string input)
{
List<string> list = new List<string>();
StreamReader reader = new StreamReader(input);
string item = "";
while (item != null)
{
item = reader.ReadLine();
if (item != null)
{
list.Add(item);
}
}
reader.Close();
return list;
for (int i = 0; i < listBox1.Items.Count; i++)
{
object url;
WebClient wc;
url = this.txtURL.Text;
wc = new WebClient();
//This should come from the proxy list
foreach (string prox in getProxyListFromText("Proxies.txt"))
{
wc.Proxy = new WebProxy(prox);
var page = wc.DownloadString(url.ToString());
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);
var pplname = doc.DocumentNode.SelectNodes("/html/body/div[3]/div/div[2]/div[2]/div/div[4]/p");
}
}
}
}
}

Categories

Resources