I am using a listBox to play file from media player on my form, I am using the code below to get files in my listbox,as it retuns the file name, now I am able to play files from listBox and now I want next item in the listbox to be played automatically after a time gap.How to do this
this.listBox1.DisplayMember = "Name";/*to display name on listbox*/
this.listBox1.ValueMember = "FullName";/*to fetch item value on listbox*/
listBox1.DataSource = GetFolder("..\\video\\"); /*gets folder path*/
private static List<FileInfo> GetFolder(string folder)
{
List<FileInfo> fileList = new List<FileInfo>();
foreach (FileInfo file in new DirectoryInfo(folder)
.GetFiles("*.mpg",SearchOption.AllDirectories))
{
fileList.Add(file);
}
return fileList;
}
for listbox I am using the following code
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
Player.URL = Convert.ToString(listBox2.SelectedItem);
}
for listBox1 I am using the code
private void listBox1_SelectedIndexChanged(object sender, EventArgs e )
{
StreamWriter sw = new StreamWriter("..\\Debug\\List.txt", true);
//Player.URL = Convert.ToString(listBox1.SelectedItem);
string selectedItem = listBox1.Items[listBox1.SelectedIndex].ToString();
//listView1.Items.Add(listBox1.SelectedItem.ToString());
foreach (object o in listBox1.SelectedItems)
sw.WriteLine(DateTime.Now + " - " + o);
sw.Close();
}
Then I am using a button to transfer selected listbox1 files to listBox2 on another form
private void button1_Click_1(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (object item in listBox1.Items)
{
sb.Append(item.ToString());
sb.Append(" ");
}
string selectedItem = listBox1.Items[listBox1.SelectedIndex].ToString();
//listBox2.Items.Add(listBox1.SelectedItem.ToString());
Form3 frm = new Form3();
foreach (int i in listBox1.SelectedIndices)
{
frm.listBox2.Items.Add(listBox1.Items[i].ToString());
frm.Show();
this.Hide();
}
}
listbox2 code is mentioned above.
You have to intercept the PlayStateChange of the player. Once you get the int value 8, which is MediaEnded, you can play the next video in the list after the desired time gap.
[UPDATE] - this does not work for .NET 2.0, so get the proper version for Form3.cs from the [EDIT] at the end of the answer
Here's Form3.cs (.NET 4.5):
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 WMPLib;
namespace WindowsFormsApplication10
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
this.listBox2.DisplayMember = "Name";/*to display name on listbox*/
this.listBox2.ValueMember = "FullName";/*to fetch item value on listbox*/
Player.PlayStateChange += Player_PlayStateChange;
}
async void Player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if ((WMPLib.WMPPlayState)e.newState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
if (listBox2.SelectedIndex + 1 < listBox2.Items.Count)
{
await System.Threading.Tasks.Task.Delay(3000);
listBox2.SelectedItem = listBox2.Items[listBox2.SelectedIndex + 1];
}
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
Player.URL = Convert.ToString(listBox2.SelectedItem.GetType().GetProperty("FullName").GetValue(listBox2.SelectedItem)).ToString();
Player.Ctlcontrols.play();
}
}
}
And here's Form1.cs (.NET 4.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 WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.listBox1.DisplayMember = "Name";/*to display name on listbox*/
this.listBox1.ValueMember = "FullName";/*to fetch item value on listbox*/
listBox1.DataSource = GetFolder("..\\video\\"); /*gets folder path*/
}
private static List<FileInfo> GetFolder(string folder)
{
List<FileInfo> fileList = new List<FileInfo>();
foreach (FileInfo file in new DirectoryInfo(folder)
.GetFiles("*.mpg", SearchOption.AllDirectories))
{
fileList.Add(file);
}
return fileList;
}
private void button1_Click(object sender, EventArgs e)
{
Form3 frm = new Form3();
frm.FormClosed += frm_FormClosed;
foreach (int i in listBox1.SelectedIndices)
{
frm.listBox2.Items.Add(new
{
Name = ((FileInfo)listBox1.Items[i]).Name,
FullName = ((FileInfo)listBox1.Items[i]).FullName
});
frm.Show();
this.Hide();
}
}
void frm_FormClosed(object sender, FormClosedEventArgs e)
{
this.Show();
}
}
}
[EDIT] - this should work for .NET 2.0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WMPLib;
namespace WindowsFormsApplication10
{
public partial class Form3 : Form
{
System.Timers.Timer _timer = new System.Timers.Timer();
object _locker = new object();
public Form3()
{
InitializeComponent();
this.listBox2.DisplayMember = "Name";/*to display name on listbox*/
this.listBox2.ValueMember = "FullName";/*to fetch item value on listbox*/
Player.PlayStateChange += Player_PlayStateChange;
_timer.Elapsed += _timer_Elapsed;
_timer.Interval = 3000;
}
void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
_timer.Stop();
lock (_locker)
{
this.Invoke((MethodInvoker)delegate
{
if (listBox2.SelectedIndex + 1 < listBox2.Items.Count)
{
listBox2.SelectedItem = listBox2.Items[listBox2.SelectedIndex + 1];
}
});
}
}
void Player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if ((WMPLib.WMPPlayState)e.newState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
_timer.Start();
}
else if ((WMPLib.WMPPlayState)e.newState == WMPLib.WMPPlayState.wmppsReady)
{
Player.Ctlcontrols.play();
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
Player.URL = Convert.ToString(listBox2.SelectedItem.GetType().GetProperty("FullName").GetValue(listBox2.SelectedItem, null)).ToString();
}
}
}
Related
I am facing a problem in my winforms app I am building in Visual Studio 2019. My app has 8 forms and I constructed a new class in which I want to save the name of the forms that users visited through a list and save them in a .txt file. I am providing you the pieces of code that I am trying to implement.
Code of one of 8 forms
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Delfoi_Tourist_Guide
{
public partial class Welcome : Form
{
SQLiteConnection connection;
private SpeechSynthesizer speech = new SpeechSynthesizer();
public Welcome()
{
InitializeComponent();
User_History.HistList.Add(this.Name);
User_History.SaveHistory();
}
private void Welcome_Load(object sender, EventArgs e)
{
String conn = "Data Source=Delfoidb1.db;Version=3";
connection = new SQLiteConnection(conn);
connection.Open(); //or Create Database
}
private void Timer1_Tick(object sender, EventArgs e)
{
label1.Show();
label2.Show();
button1.Visible = true;
button2.Visible = true;
timer2.Enabled = true;
timer1.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
if (speech.State == SynthesizerState.Speaking)
{
speech.Pause();
}
Form2 form2 = new Form2();
form2.Show();
this.Visible = false;
}
private void button6_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void timer2_Tick(object sender, EventArgs e)
{
speech.SelectVoice("Microsoft Stefanos");
speech.SpeakAsync(label2.Text);
timer2.Enabled = false;
}
private void button2_Click(object sender, EventArgs e)
{
if (speech.State == SynthesizerState.Speaking)
{
speech.Pause();
}
Form8 form8 = new Form8();
form8.Show();
this.Visible = false;
}
private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
{
MessageBox.Show("Developed by Ανδρέας Κρεούζος(ΜΠΠΛ20040) and Δημήτρης Γιογάκης(ΜΠΠΛ20008)");
}
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
//Implement try - catch to avoid exception specifically for url error
try
{
Help.ShowHelp(this, "_tmphhp/Delfoi_Tourist_Guide_Help.chm", HelpNavigator.KeywordIndex, "Topic 1");
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
if (speech.State == SynthesizerState.Speaking)
{
speech.Pause();
}
Welcome welcome = new Welcome();
welcome.Show();
this.Visible = false;
}
private void έξοδοςToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Code of the separate class that saves the data as txt
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Delfoi_Tourist_Guide
{
public static class User_History
{
public static List<string> HistList = new List<string>();
public static void SaveHistory()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog.FileName;
StreamWriter sw = new StreamWriter(path);
sw.WriteLine(HistList);
sw.Close();
}
}
}
}
My problem is that I can't transfer the data (placed on the InitializeComponent) from forms to my class. I am getting my txt file with nothing in it. My data is actually saved on my public static list but I can't transfer it next to the rest of my User_History class.
Any ideas on how to accomplish this???
You can try this SaveHistory() method
public static void SaveHistory()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog.FileName;
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (string history in HistList)
{
writer.WriteLine(history);
}
}
}
}
in my current project ,i have a form which contains 2 command buttons named COPY and Cancel
if i click COPY button it is copying 3000 files from source directory to a destination directory ,at the same time if click the Cancel Button , it should cancel the copy and exit the form. is there any way to do so?
i applied the solution but got errors. i have the following 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.Threading;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
private volatile bool _continue = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
_continue = true;
System.Threading.ThreadStart ts = new ThreadStart(print_number);
System.Threading.Thread t = new Thread(ts);
t.Start();
}
private void print_number()
{
for (int i = 1; i <= 10000; i++)
{
textBox1.Text = Convert.ToString(i);
if (_continue == false)
{
return;
}
//Thread.Sleep(2000);
}
}
private void button2_Click(object sender, EventArgs e)
{
_continue = false;
Close();
}
}
}
Example:
private volatile bool _continue = false;
private void CopyClicked(Object sender, EventArgs e)
{
_continue = true;
System.Threading.ThreadStart ts = new ThreadStart(CopyFiles);
System.Threading.Thread t = new Thread(ts);
t.Start();
}
private void CopyFiles(){
List<String> list = GetFileNames();
foreach( String f in list )
{
if ( _continue == false )
{
return;
}
CopyFile(s); //examples...
}
}
private void CancelClicked(Object sender, EventArgs e)
{
_continue = false;
Close();
}
I have two forms, one is for the text editor, and the second is for the search form.
In my Form1 I have defined the GetRichTextBox() function. It works there, how could I retrieve it to Form2 (and the other stuff)?
My Form1:
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 TextEditor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private RichTextBox GetRichTextBox()
{
RichTextBox rtb = null;
TabPage tp = tabControl1.SelectedTab;
if (tp != null)
{
rtb = tp.Controls[0] as RichTextBox;
}
return rtb;
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
TabPage tp = new TabPage("doc");
RichTextBox rtb = new RichTextBox();
rtb.Dock = DockStyle.Fill;
tp.Controls.Add(rtb);
tabControl1.TabPages.Add(tp);
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
GetRichTextBox().Cut();
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
GetRichTextBox().Copy();
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
GetRichTextBox().Paste();
}
private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
GetRichTextBox().Undo();
}
private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
GetRichTextBox().Redo();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFD = new OpenFileDialog();
string Chosen_File = "";
openFD.InitialDirectory = "C:";
openFD.Title = "Open a Text File";
openFD.FileName = "";
openFD.Filter = "Text Files|*.txt|Word Documents|*.doc";
if (openFD.ShowDialog() != DialogResult.Cancel)
{
Chosen_File = openFD.FileName;
TabPage tab = new TabPage() { Text = System.IO.Path.GetFileName(Chosen_File) };
tabControl1.TabPages.Add(tab);
tabControl1.SelectedTab = tab;
RichTextBox box = new RichTextBox { Parent = tab, Dock = DockStyle.Fill };
box.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFD = new SaveFileDialog();
string saved_file = "";
saveFD.InitialDirectory = "C:";
saveFD.Title = "Save a Text File";
saveFD.FileName = "";
saveFD.Filter = "Text Files|*.txt|Word Documents|*.doc";
if (saveFD.ShowDialog() != DialogResult.Cancel)
{
saved_file = saveFD.FileName;
GetRichTextBox().SaveFile(saved_file, RichTextBoxStreamType.PlainText);
MessageBox.Show("Your file has been successfully saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure?", "Exit", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
Application.Exit();
}
}
private void closeTabToolStripMenuItem_Click(object sender, EventArgs e)
{
TabPage active_tab = tabControl1.SelectedTab;
tabControl1.TabPages.Remove(active_tab);
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
var search = new Form2();
search.ShowDialog();
}
}
}
And ofcourse, my Form2:
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 TextEditor
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int index = 0; string temp = richTextBox1.Text; richTextBox1.Text = ""; richTextBox1.Text = temp;
while (index < richTextBox1.Text.LastIndexOf(textBox1.Text))
{
richTextBox1.Find(textBox1.Text, index, richTextBox1.TextLength, RichTextBoxFinds.None);
richTextBox1.SelectionBackColor = Color.Orange;
index = richTextBox1.Text.IndexOf(textBox1.Text, index) + 1;
}
}
}
}
I am really stuck with this so I hope someone can help. I have 2 winforms, one has a listview and another has a textbox. I want to check which item is checked in the listview and copy this text into the second form. I have tried this code but it won't work, any help is greatly appreciated!
// 1st form
private void button5_Click(object sender, EventArgs e) // Brings up the second form
{
Form4 editItem = new Form4();
editItem.Show();
}
public string GetItemValue()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
return listView1.Items[i].Text;
}
}
return "Error";
}
// 2nd form
private void Form4_Load(object sender, EventArgs e)
{
Form1 main = new Form1();
textBox1.Text = main.GetItemValue();
}
You are creating a new Form1 inside of Form4 after it has been loaded. You need a reference to the original Form1. This can be accomplished in several ways, probably the easiest is passing a reference into the Form4 constructor.
// Form 1
// This button creates a new "Form4" and shows it
private void button5_Click(object sender, EventArgs e)
{
Form4 editItem = new Form4(this);
editItem.Show();
}
public string GetItemValue()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
return listView1.Items[i].Text;
}
}
return "Error";
}
--
// Form 2 (Form4)
// Private member variable / reference to a Form1
private Form1 _form;
// Form4 Constructor: Assign the passed-in "Form1" to the member "Form1"
public Form4(Form1 form)
{
this._form = form;
}
// Take the member "Form1," get the item value, and write it in the text box
private void Form4_Load(object sender, EventArgs e)
{
textBox1.Text = this._form.GetItemValue();
}
You only need a couple of changes. No need to add your own way of storing the owner form as this functionality already exists.
private void button5_Click(object sender, EventArgs e) // Brings up the second form
{
Form4 editItem = new Form4();
editItem.Show(this); //passes a reference to this form to be stored in owner
}
Then reference it on the other form.
private void Form4_Load(object sender, EventArgs e)
{
textBox1.Text = ((Form1)owner).GetItemValue();
}
Try thisway
FORM 1
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
//Fields
public List<string> itemTexts;
public Form1()
{
InitializeComponent();
//Generate some items
for (int i = 0; i < 10; i++)
{
ListViewItem item = new ListViewItem();
item.Text = "item number #" + i;
listView1.Items.Add(item);
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in listView1.Items)
{
if (item.Checked)
{
itemTexts.Add(item.Text);
}
}
Form2 TextBoxForm = new Form2(itemTexts);
TextBoxForm.Show();
}
}
}
FORM 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;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
//Fields
List<string> itemTexts;
public Form2(List<string> itemTexts)
{
InitializeComponent();
this.itemTexts = itemTexts;
foreach (string text in itemTexts)
{
textBox1.Text += text + Environment.NewLine;
}
}
}
}
My problem is I can not see any thing on form when I run application. This my code:
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 GMap;
using GMap.NET;
using GMap.NET.WindowsForms;
namespace Gmap_tesx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e1)
{
try
{
System.Net.IPHostEntry e =
System.Net.Dns.GetHostEntry("www.google.com");
}
catch
{
gMapControl1.Manager.Mode = AccessMode.CacheOnly;
MessageBox.Show("No internet connection avaible, going to CacheOnly mode.",
"GMap.NET - Demo.WindowsForms", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
// config map
GMaps.Instance.Mode = AccessMode.ServerAndCache;
// gMapControl1.CacheLocation = Application.StartupPath + "data.gmdp";
GMaps g = new GMaps();
gMapControl1.MapType = MapType.GoogleSatellite;
gMapControl1.MaxZoom = 6;
gMapControl1.MinZoom = 1;
gMapControl1.Zoom = gMapControl1.MinZoom + 1;
gMapControl1.Position = new PointLatLng(54.6961334816182,
25.2985095977783);
// map events
gMapControl1.OnCurrentPositionChanged += new
CurrentPositionChanged(gMapControl1_OnCurrentPositionChanged);
gMapControl1.OnTileLoadStart += new TileLoadStart(gMapControl1_OnTileLoadStart);
gMapControl1.OnTileLoadComplete += new
TileLoadComplete(gMapControl1_OnTileLoadComplete);
gMapControl1.OnMarkerClick += new MarkerClick(gMapControl1_OnMarkerClick);
gMapControl1.OnMapZoomChanged += new MapZoomChanged(gMapControl1_OnMapZoomChanged);
gMapControl1.OnMapTypeChanged += new MapTypeChanged(gMapControl1_OnMapTypeChanged);
gMapControl1.MouseMove += new MouseEventHandler(gMapControl1_MouseMove);
gMapControl1.MouseDown += new MouseEventHandler(gMapControl1_MouseDown);
gMapControl1.MouseUp += new MouseEventHandler(gMapControl1_MouseUp);
gMapControl1.OnMarkerEnter += new MarkerEnter(gMapControl1_OnMarkerEnter);
gMapControl1.OnMarkerLeave += new MarkerLeave(gMapControl1_OnMarkerLeave);
}
private void gMapControl1_OnCurrentPositionChanged(PointLatLng point)
{
}
private void gMapControl1_OnMarkerLeave(GMapMarker item)
{
}
private void gMapControl1_OnMarkerEnter(GMapMarker item)
{
}
private void gMapControl1_MouseUp(object sender, MouseEventArgs e)
{
}
private void gMapControl1_MouseDown(object sender, MouseEventArgs e)
{
}
private void gMapControl1_MouseMove(object sender, MouseEventArgs e)
{
}
private void gMapControl1_OnMapTypeChanged(MapType type)
{
}
private void gMapControl1_OnMapZoomChanged()
{
}
private void gMapControl1_OnMarkerClick(GMapMarker item, MouseEventArgs e)
{
}
private void gMapControl1_OnTileLoadComplete(long ElapsedMilliseconds)
{
}
private void gMapControl1_OnTileLoadStart()
{
}
}
}