Windows Forms text editor search function - c#

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;
}
}
}
}

Related

Communication between 2 Form in C#(Keep connecting from Fom1 for Form2) [duplicate]

This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I am a newbie in C# and I have questions as below:
I have a Form1 name is setting Port Name, Baud Rate, Parity... of modbus protocol and I can open serial Port.
Also, I have another Form is called Form2, When Port is opened i want to close Form1 and Port alway Open => I can do it. But this problem that was I want to get data such as FC03 HolodingRegister, FC01 WriteSingleCoil... for Form2 but didnot.
I used delegate to transfer data from Form 1 to Form 2 but I could not use button Form2 to send FC01 signal.
How to use FC01, FC03,04... for Form2 when Form 1 connected.
Code 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;
using System.IO.Ports;
using Modbus.Device;
namespace ATS
{
public partial class frCommunication : Form
{
SerialPort serialPort = new SerialPort();
ModbusMaster Master;
public delegate void truyendulieu(string text);
public truyendulieu truyendata;
public delegate void truyendulieu1(string text1);
public truyendulieu1 truyendata1;
public delegate void truyendulieu2(string text2);
public truyendulieu2 truyendata2;
public frCommunication()
{
InitializeComponent();
}
private void frCommunication_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
cboxPort.Items.AddRange(ports);
cboxPort.SelectedIndex = 0;
}
private void btnConnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
try
{
serialPort.PortName = cboxPort.Text;
serialPort.BaudRate = Convert.ToInt32(cboxBaudRate.Text);
serialPort.DataBits = Convert.ToInt32(cboxDataBits.Text);
serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboxStopBits.Text);
serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboxParity.Text);
serialPort.Open();
Master = ModbusSerialMaster.CreateRtu(serialPort);
Master.Transport.Retries = 0; // don't have to to retries
Master.Transport.ReadTimeout = 300;//miliseconds
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (serialPort.IsOpen)
{
lblDisplay.Text = "Connected";
lblDisplay.ForeColor = System.Drawing.Color.Red;
cboxBaudRate.Enabled = false;
}
else
{
lblDisplay.Text = "Disconnected";
MessageBox.Show("Error!");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
try
{
serialPort.Close();
lblDisplay.Text = "Disconnected";
lblDisplay.ForeColor = System.Drawing.Color.Green;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
ushort[] holding_register = Master.ReadHoldingRegisters(1, 0, 10);
txtV_Grid.Text = Convert.ToString(holding_register[0]);
txtC_Grid.Text = Convert.ToString(holding_register[1]);
txtP_Grid.Text = Convert.ToString(holding_register[2]);
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (txtV_Grid.Text.Length > 0 || txtC_Grid.Text.Length > 0 || txtP_Grid.Text.Length > 0)
{
if (truyendata != null || truyendata1 != null)
{
truyendata(txtV_Grid.Text);
truyendata1(txtC_Grid.Text);
truyendata2(txtP_Grid.Text);
}
this.Hide();
}
}
private void txtV_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata != null)
{
truyendata(txtV_Grid.Text);
}
}
private void txtC_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata1 != null)
{
truyendata1(txtC_Grid.Text);
}
}
private void txtP_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata2 != null)
{
truyendata2(txtP_Grid.Text);
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void btnOn_ACB_Grid_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
DialogResult dl = MessageBox.Show("Would you like to turn On ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dl == DialogResult.Yes)
{
Master.WriteSingleCoil(1, 0, true);
}
else
{
Master.WriteSingleCoil(1, 0, false);
}
}
}
private void btnOff_ACB_Grid_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
DialogResult dl = MessageBox.Show("Would you like to turn Off ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dl == DialogResult.Yes)
{
Master.WriteSingleCoil(1, 0, false);
}
else
{
Master.WriteSingleCoil(1, 0, true);
}
}
}
}
}
Code 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;
using SymbolFactoryDotNet;
namespace ATS
{
public partial class frMain : Form
{
public frMain()
{
InitializeComponent();
}
private void communicationToolStripMenuItem_Click(object sender, EventArgs e)
{
frCommunication frm = new frCommunication();
frm.ShowDialog();
}
private void standardControl1_Load(object sender, EventArgs e)
{
}
private void LoadData(string data)
{
txtV.Text = "";
txtV.Text = data;
}
private void LoadData1(string data1)
{
txtC.Text = "";
txtC.Text = data1;
}
private void LoadData2(string data2)
{
txtP.Text = "";
txtP.Text = data2;
}
private void btnConnect_Click(object sender, EventArgs e)
{
frCommunication frm = new frCommunication();
frm.truyendata = new frCommunication.truyendulieu(LoadData);
frm.truyendata1 = new frCommunication.truyendulieu1(LoadData1);
frm.truyendata2 = new frCommunication.truyendulieu2(LoadData2);
frm.ShowDialog();
}
private void txtV_TextChanged(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
if(picOn.Visible == false)
{
picOn.Visible = true;
picOff_Grid.Visible = false;
// standardControl3.DiscreteValue2 = true;
}
else
{
picOn.Visible = false;
picOff_Grid.Visible = true;
}
}
private void frMain_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("HH:mm:ss dd-MM-yyyy");
}
private void btnOn_Grid_Click(object sender, EventArgs e)
{
}
}
}
When I understand you right, you will in Form1 open a connection, close the Form, open a new Form2 and use this connection there?
Well, when that's the case, you could make an special Connection Singleton to hold this connection then you can use it in your Form2
using System;
namespace Sandbox
{
public sealed class Connection
{
private static readonly Lazy<Connection> _instance = new Lazy<Connection>(() => new Connection());
public static Connection Instance => _instance.Value;
private Connection()
{ }
// Implement your Connection Code here.
}
}

Transfer values from one class to another using a list

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);
}
}
}
}

Why do I cannot create a new Tab from another Form?

I want to call the NewTab() function from another form. But it doesn't work. I'm new to C# and Programming and need help.
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;
using CefSharp;
using CefSharp.WinForms;
namespace Browser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ChromiumWebBrowser chrome;
private void Window_Load(object sender, EventArgs e)
{
CefSettings settings = new CefSettings();
Cef.Initialize(settings);
txtUrl.Text = "https://google.com";
chrome = new ChromiumWebBrowser(txtUrl.Text);
chrome.Parent = tabControl.SelectedTab;
chrome.Dock = DockStyle.Fill;
chrome.AddressChanged += Chrome_AddressChanged;
chrome.TitleChanged += Chrome_TitleChanged;
}
private void Chrome_AddressChanged(object sender, AddressChangedEventArgs e)
{
this.Invoke(new MethodInvoker(() =>
{
txtUrl.Text = e.Address;
}));
}
private void buttonRefresh_Click(object sender, EventArgs e)
{
ChromiumWebBrowser chrome = tabControl.SelectedTab.Controls[0] as ChromiumWebBrowser;
if (chrome != null)
{
chrome.Refresh();
}
}
private void buttonNavigate_Click(object sender, EventArgs e)
{
ChromiumWebBrowser chrome = tabControl.SelectedTab.Controls[0] as ChromiumWebBrowser;
if(chrome != null)
{
chrome.Load(txtUrl.Text);
}
}
private void buttonForward_Click(object sender, EventArgs e)
{
ChromiumWebBrowser chrome = tabControl.SelectedTab.Controls[0] as ChromiumWebBrowser;
if (chrome != null)
{
if (chrome.CanGoForward)
{
chrome.Forward();
}
}
}
private void buttonBack_Click(object sender, EventArgs e)
{
ChromiumWebBrowser chrome = tabControl.SelectedTab.Controls[0] as ChromiumWebBrowser;
if (chrome != null)
{
if(chrome.CanGoBack)
{
chrome.Back();
}
}
}
private void Window_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
public void btnNewTab_Click(object sender, EventArgs e)
{
NewTab("https://google.com");
}
public void NewTab(string url)
{
TabPage tab = new TabPage();
tab.Text = "New Tab";
tabControl.Controls.Add(tab);
tabControl.SelectTab(tabControl.TabCount - 1);
ChromiumWebBrowser chrome = new ChromiumWebBrowser(url);
chrome.Parent = tab;
chrome.Dock = DockStyle.Fill;
txtUrl.Text = url;
chrome.AddressChanged += Chrome_AddressChanged;
chrome.TitleChanged += Chrome_TitleChanged;
}
private void Chrome_TitleChanged(object sender, TitleChangedEventArgs e)
{
this.Invoke(new MethodInvoker(() =>
{
tabControl.SelectedTab.Text = e.Title;
}));
}
private void closeTabToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl.Controls.Remove(tabControl.SelectedTab);
}
private void openMultipleTabsToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}
}
}
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 Browser
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.NewTab("https://google.com");
}
}
}
I try to make a Webbrowser with special features. I use CefSharp for this. Sorry for the ugly Code I'm new to C# and Programming. Got most of this from a Youtube tutorial. I'm trying to make another window that you can open with a menustrip that lets you open multiple tabs at once. But for now, I don't even get one new Tab opened. It could be nice if you help me with this.
You create a new instance of Form1 but you don't show it.
Try this:
private void button1_Click(object sender, EventArgs e)
{
Form1 form = new Form1();
form.NewTab("https://google.com");
form.Show();
}

serialport1 does not exist in context

using System.Collections.Generic;
using System.ComponentModel;
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsFormsApplication21
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
button1.BackColor = Color.Red;
label1.Text = " OCCUPIED";
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
this.Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
string InputString = serialPort1.ReadExisting();
string[] data = InputString.Split(',');
textBox1.Text = data[0];
textBox2.Text = data[1];
int b;
int d;
bool result = Int32.TryParse(data[0], out b);
bool sonuc = Int32.TryParse(data[1], out d);
if (result)
{
if (b < 224)
{
button1.BackColor = Color.Red;
label1.Text = " OCCUPIED";
}
else
{
button1.BackColor = Color.Lime;
label1.Text = "AVAILABLE";
}
}
if (sonuc)
{
if (d< 224)
{
button1.BackColor = Color.Red;
label1.Text = " OCCUPIED";
}
else
{
button1.BackColor = Color.Lime;
label1.Text = "AVAILABLE";
}
}
int b = Int16.Parse(a);
textBox1.Text= a.ToString();*/
private void button3_Click(object sender, EventArgs e)
{
listBox1.Visible = true;
listBox1.Items.Add("Değerler alınıyor!");
if (!serialPort1.IsOpen)
{
serialPort1.PortName = "COM11";
serialPort1.Open();
}
}
private void button4_Click(object sender, EventArgs e)
{
serialPort1.Close();
listBox1.Items.Add("Durduruldu!");
}
}
}
I am getting an error:
"serialport1 does not exist in context"
What can l do? Whenever I want to compile I get the above mention error.
Do I have to add any library?
I am using visual Studio 2010

How to automatically play next item of a listBox

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();
}
}
}

Categories