RichTextBox to BackgroundWorker - c#

How can I throw RichTextBox1's value to a BackgroundWorker in C#?
public void button4_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(richTextBox1.Text.Trim())){
MessageBox.Show("No value in RichTextBox?");
return;
}
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync(richTextBox1);
}
Here's my BackgroundWorker's code:
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
foreach (string vr in richTextBox1.Lines)
{
⋮
}
}

You can't pass the RichTextBox for reasons given above, but you can pass in the string array which is the RichTextBox.Lines Property and iterate through that.
private void button1_Click(object sender, EventArgs e)
{
bg.RunWorkerAsync(richTextBox1.Lines);
}
void bg_DoWork(object sender, DoWorkEventArgs e)
{
string[] lines = (string[])e.Argument;
foreach(string vr in lines)
{
}
}

private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync(richTextBox1.Text);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string text = (string)e.Argument;
MessageBox.Show(text);
}
The text is sent as object e.argument. To retrieve it cast e.argument back to a string (or string[] etc depending on what you pass)

Usually only the Main UI thread can interact with Forms and Controls.
Consider passing all the data it needs to the RunWorkerAsync method -- perhaps RunWorkerAsync(richTextBox1.Lines.ToList()).

Related

serial port reading multiple lines

I have a board which I am trying to communicate with. When I give it some commands it should return string messages back and should get posted in a textbox. My problem is when the device has to return multiple lines of text only 1 of the lines gets posted. I have tried also with ReadExisting instead of ReadLine but after one command I get only empty strings back.
public partial class Form1 : Form
{
private string x;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.Open();
timer1.Start();
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(textBox1.Text);
textBox1.Clear();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(x))
{
}
else
{
textBox2.AppendText(x + "\n\r");
x = "";
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
x = serialPort1.ReadLine();
//x = serialPort1.ReadExisting();
}
private void Form1_Closing(object sender, EventArgs e)
{
serialPort1.Close();
timer1.Stop();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
You're always better off avoiding DataReceived and just using BaseStream. Like this:
private async void Form1_Load(object sender, EventArgs e)
{
serialPort1.Open();
using (var reader = new StreamReader(serialPort1.BaseStream)) {
while (serialPort1.IsOpen) {
string x = await reader.ReadLineAsync();
textBox2.AppendText(x + "\r\n");
}
}
}
The await keyword silently manages synchronization back to the UI thread -- you don't need Invoke, you don't get cross-thread failures, you don't get a second invocation of your event handler triggered while the first one is still running, you don't get race conditions from multiple threads accessing the same variable. Much easier to get right.
As a style issue, I wouldn't put this code directly in your Form Load event handler, I would put it in a suitably named helper function (OpenAndReadSerial() perhaps) and call that from overridden OnLoad().

How can i update listView or labels and report to backgroundworker progress changed without using invoke?

I'm not sure if invoke is the right way to use it. It's working fine but i wonder if i should use invoke or some other way to update gui controls ? And if i want to report to more then 1 gui control ?
Now i'm updating label2 and a listView controls using invoke.
When should i use invoke and when not and then how to update this gui controls without invoking ?
private string pathtosearch;
private int countfiles;
public Form1()
{
InitializeComponent();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DirSearch(pathtosearch);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d))
{
Invoke((MethodInvoker)delegate
{
countfiles += 1;
label2.Text = countfiles.ToString();
});
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Invoke((MethodInvoker)delegate
{
ListViewCostumControl.lvnf.Items.Add(excpt.Message);
});
}
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
label1.Text = folderBrowserDialog1.SelectedPath;
pathtosearch = folderBrowserDialog1.SelectedPath;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.TextLength > 0)
backgroundWorker1.RunWorkerAsync();
}
Use the ReportProgress method to send Message to UI and ProgressChanged event to handle the message.
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
var ex = e.UserState as Exception;
if(ex!= null)
ListViewCostumControl.lvnf.Items.Add(ex.Message);
else
label2.Text = e.ProgressPercentage.ToString();;
}
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d))
backgroundWorker1.ReportProgress(countfiles++);
DirSearch(d);
}
}
catch (System.Exception excpt)
{
backgroundWorker1.ReportProgress(countfiles, excpt);
}
}
ReportProgress can overloaded with two argument: one numeric to report simple "Progress", an thesecond called UserData of type object. if you want send rich information, insert in this argument your custom object or any other existing with the required properties, and on the other side - in ProgressChanged event, "cast" it again to the appropriate type, example:
ReportProgress:
backgroundWorker1.ReportProgress(countfiles, Tuple.Create(currFile, "Copying...", timeRem));
ProgressChanged event:
var data = e.UserState as Tuple<string, string, TimeSpan>;

Can't put more than one number in the textbox. in my Simple Calculator program

Need help in making a simple calculator. i can't put more than one number in my calculator's textbox. Everytime i put a second number it replaces the first one need help!
I can't exceed more than one input number in my Calculator's Textbox instead it replaces the first number with a second number input
namespace Calculator_Project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void InputOutputArea_TextChanged(object sender, EventArgs e)
{
}
private void One_Click(object sender, EventArgs e)
{
int Input = 1;
InputOutputArea.Text = Input.ToString();
}
private void Two_Click(object sender, EventArgs e)
{
int Input = 2;
InputOutputArea.Text = Input.ToString();
}
private void Three_Click(object sender, EventArgs e)
{
}
private void Four_Click(object sender, EventArgs e)
{
}
private void Five_Click(object sender, EventArgs e)
{
}
private void Six_Click(object sender, EventArgs e)
{
}
private void Seven_Click(object sender, EventArgs e)
{
}
private void Eight_Click(object sender, EventArgs e)
{
}
private void Nine_Click(object sender, EventArgs e)
{
}
private void Eql_Click(object sender, EventArgs e)
{
}
private void AddB_Click(object sender, EventArgs e)
{
}
private void Minus_Click(object sender, EventArgs e)
{
}
private void MultiplyB_Click(object sender, EventArgs e)
{
}
private void DivideB_Click(object sender, EventArgs e)
{
}
private void Zero_Click(object sender, EventArgs e)
{
}
private void ResetB_Click(object sender, EventArgs e)
{
InputOutputArea.Clear();
}
}
}
You should use
InputOutputArea.Text += Input.ToString();
(note the '+') in order to append to a text box.
private void Two_Click(object sender, EventArgs e)
{
int Input = 2;
InputOutputArea.Text += Input.ToString();
}
You must use += to add other text to next of first text
Here is your problem:
InputOutputArea.Text = Input.ToString();
This replaces the content of the textbox instead of adding to it.
InputOutputArea.Text += Input.ToString();
the above code should do as you ask.
Good to remember is that concatenating strings with + is rather inefficient, so don't do this in performance critical code unless absolutely necessary. In those cases a String-builder is almost always better.
Every answers talking about the Concatenation of the previous text with the current, But I would like to suggest something more than that;
You need not to create separate event handlers for all your buttons that are doing same tasks, Hope that the Text of each button will be the number that you need to display in the textBox(say btnOne will holds 1 and btnTwoholds 2 and so on). By make use of this Text we can reuse the handlers like the following, Let btnNumber_Click be the handler and which is defined like the following:
private void btnNumber_Click(object sender, EventArgs e)
{
Button currentButton = sender as Button;
InputOutputArea.Text += currentButton.Text;
}

How to call this method in a background worker?

I am a beginner in C# and WPF and I am building this project in which I have to trigger when the mouse is moved. Under some conditions, I have to use it as a background worker. I want to call the mouse_Moved method in the background, but I don't know how to actually do that . Can anyone help me please? This is my code so far:
public MainWindow()
{
InitializeComponent();
mouse = new MouseInput();
mouse.MouseMoved += mouse_MouseMoved;
}
void mouse_MouseMoved(object sender, EventArgs e)
{
//The code that I need
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
//where I want to call the mouse_Moved method
}
Create a method and call it from both:
void mouse_MouseMoved(object sender, EventArgs e)
{
DoMouseMovedWork();
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
DoMouseMovedWork();
}
private DoMouseMovedWork()
{
//The code I need
}

Update Tab's Name in C# Web Browser

I'm working on a Web browser in Visual Studio 2010, but I can't update the tab's name to the website's name. For example, when you visit a website like CNN.Com, I want the tab to also say, "cnn.com". The project isn't using the default WebBrowser form, by the way. Please explain it in the simplest way possible since I'm new to C#(Just moved from C++ and Java) so I'm not familiar with working with Windows forms. Thanks. Any help is appreciated.
Here's an image of the problem: http://postimage.org/image/5ym4yx0pt/
....
public Form1()
{
InitializeComponent();
}
int i = 1;
private void Form1_Load(object sender, EventArgs e)
{
WebBrowser Browse = new WebBrowser();
//Load a tab when loading form
tabControl1.TabPages.Add("Tab");//problem
tabControl1.SelectTab(i - 1);
Browse.Name = "Lithium Browser";
Browse.Dock = DockStyle.Fill;
tabControl1.SelectedTab.Controls.Add(Browse);
i++;
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate("www.google.com");
}
private void button1_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(textBox1.Text);
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
WebBrowser Browse = new WebBrowser();
tabControl1.TabPages.Add("Tab"); //problem
tabControl1.SelectTab(i - 1);
Browse.Name = "Lithium Browser";
Browse.Dock = DockStyle.Fill;
tabControl1.SelectedTab.Controls.Add(Browse);
i++;
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
tabControl1.TabPages.RemoveAt(tabControl1.SelectedIndex);
tabControl1.SelectTab(tabControl1.TabPages.Count - 1);
i = i- 1;
}
private void toolStripButton3_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).GoBack();
}
private void toolStripButton4_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).GoForward();
}
private void toolStripButton5_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).GoHome();
}
private void toolStripButton6_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Refresh();
}
private void toolStripButton7_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Stop();
}
private void yahooSearchToolStripMenuItem_Click(object sender, EventArgs e)
{
toolStripDropDownButton1.Text = yahooSearchToolStripMenuItem.Text;
}
private void youtubeSearchToolStripMenuItem_Click(object sender, EventArgs e)
{
toolStripDropDownButton1.Text = youtubeSearchToolStripMenuItem.Text;
}
private void googleSearchToolStripMenuItem_Click(object sender, EventArgs e)
{
toolStripDropDownButton1.Text = googleSearchToolStripMenuItem.Text;
}
private void toolStripButton8_Click(object sender, EventArgs e)
{
if (toolStripDropDownButton1.Text == googleSearchToolStripMenuItem.Text)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate("http://www.google.com/search?q=" + toolStripTextBox1.Text);
}
if (toolStripDropDownButton1.Text == yahooSearchToolStripMenuItem.Text)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate("http://search.yahoo.com/search?p=" + toolStripTextBox1.Text);
}
if (toolStripDropDownButton1.Text == youtubeSearchToolStripMenuItem.Text)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate("http://www.youtube.com/results?search_query=" + toolStripTextBox1.Text);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
//add KeyUp event for detecting 'Enter' key
//navigate to specified URL withoud pressing the 'Go' button
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(textBox1.Text);
}
}
private void toolStripTextBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (toolStripDropDownButton1.Text == googleSearchToolStripMenuItem.Text)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate("http://www.google.com/search?q=" + toolStripTextBox1.Text);
}
if (toolStripDropDownButton1.Text == yahooSearchToolStripMenuItem.Text)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate("http://search.yahoo.com/search?p=" + toolStripTextBox1.Text);
}
if (toolStripDropDownButton1.Text == youtubeSearchToolStripMenuItem.Text)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate("http://www.youtube.com/results?search_query=" + toolStripTextBox1.Text);
}
if (toolStripDropDownButton1.Text == youtubeSearchToolStripMenuItem.Text)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate("http://en.wikipedia.org/wiki/" + toolStripTextBox1.Text);
}
if (toolStripDropDownButton1.Text == youtubeSearchToolStripMenuItem.Text)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Navigate("http://en.wikipedia.org/wiki/" + toolStripTextBox1.Text);
}
}
}
private void newTabToolStripMenuItem_Click(object sender, EventArgs e)
{
WebBrowser Browse = new WebBrowser();
tabControl1.TabPages.Add("Tab");
tabControl1.SelectTab(i - 1);
Browse.Name = "Lithium Browser";
Browse.Dock = DockStyle.Fill;
tabControl1.SelectedTab.Controls.Add(Browse);
i++;
}
private void closeTabToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl1.TabPages.RemoveAt(tabControl1.SelectedIndex);
tabControl1.SelectTab(tabControl1.TabPages.Count - 1);
i = i - 1;
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
}
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
printDialog.ShowDialog();
}
private void printPreviewDialog1_Load(object sender, EventArgs e)
{
}
private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
{
//Associate PrintPreviewDialog with PrintDocument.
printPreviewDialog1.Document = printDocument1;
// Show PrintPreview Dialog
printPreviewDialog1.ShowDialog();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Exit?", "Exit", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
Application.Exit();
}
}
// Bring up 'Print Dialog'
private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e)
{
PageSetupDialog pageSetup = new PageSetupDialog();
pageSetup.PrinterSettings = new System.Drawing.Printing.PrinterSettings();
pageSetup.PageSettings = new System.Drawing.Printing.PageSettings();
pageSetup.EnableMetric = false;
pageSetup.ShowDialog();
}
private void stopToolStripMenuItem_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Stop();
}
private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).Refresh();
}
private void homeToolStripMenuItem_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).GoHome();
}
private void previousPageToolStripMenuItem_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).GoBack();
}
private void nextPageToolStripMenuItem_Click(object sender, EventArgs e)
{
((WebBrowser)tabControl1.SelectedTab.Controls[0]).GoForward();
}
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 about = new Form2();
about.Show();
}
private void calenderToolStripMenuItem_Click(object sender, EventArgs e)
{
calenForm cal = new calenForm();
cal.Show();
}
}
}
...........
Assuming WebBrowser is the built-in WebBrowser, you can fire the OnDocumentTitleChanged event to change the tab text every time the WebBrowser document title is changed.
to do this, in the form load event, after declaring browse, start typing browse.DocumentTitleChanged += and a tooltip should come up saying 'tab to insert this code' or something along those lines. Just tab twice and Visual Studio will insert a new method for you, with a throw new NotImplementedException(); line. Delete that line and replace it with the code changing your tab's text to the browser's DocumentTitle.
If you need any more information, I suggest you check the documentation:
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx
Though I am confident that using events is the best solution. Events are designed to execute upon certain significant programming 'events' happening, and changing a webpage is one example of such an event. (Events are roughly C#'s equivalent of C++'s function pointers if that helps your understanding at all. Though they are more akin to a std::vector of function pointers.)
Set the HTML title tag for the page text contained within the two tags will show up in the tab that the web page is displayed in.
See the following for more about setting the title in the code behind
How to use Eval in codebehind to set Page.Title
And this link as well
http://www.asprobot.com/ASP.NET/ASPNET-Title-Tag-and-Meta-Tags

Categories

Resources