How can I use invoke for fixing exception error? - c#

I am trying to write a code for taking fps at label while taking view from the camera.
So, I used task for that and I used timer but I got an error. I fixed the problem with using CheckForIllegalCrossThreadCalls = false; but as far as I know it is not an effective way.
I want to fix this with using invoke. How should I write the code properly?
Here is the code:
using System;
using System.Drawing;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace projectimg
{
public partial class Form1 : Form
{
Stopwatch watch = new Stopwatch();
System.Timers.Timer timerFPS;
public Form1()
{
InitializeComponent();
}
CameraConnection connnection;
private bool btn_GetviewWasClicked = false;
private void Form1_Load(object sender, EventArgs e)
{
btn_Getview.Click += Btn_Getview_Click;
timerFPS = new System.Timers.Timer(1000);
timerFPS.Elapsed += TimerFPS_Elapsed;
timerFPS.Start();
}
private void Btn_Getview_Click(object sender, EventArgs e)
{
btn_GetviewWasClicked = true;
Task.Run(() =>
{
connnection = new CameraConnection();
connnection.Connect();
});
CameraConnection.DataReceived += CameraConnection_DataReceived;
}
private void TimerFPS_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
txt_fps.Text = Convert.ToString(CameraConnection.count);
CameraConnection.count = 0;
}
}
}

Related

How to download the first item in a page after the page complete loading

I want to download the specific file (the first item of the page) from a website, below is my code
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
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 WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitializeAsyc();
}
async void InitializeAsyc()
{
await webView21.EnsureCoreWebView2Async(null);
webView21.CoreWebView2.Navigate("https://www.moodys.com");
}
private async void button1_Click(object sender, EventArgs e)
{
var checkJs = "document.documentElement.innerText.indexOf('Sign In or Register')>-1";
string res = await webView21.CoreWebView2.ExecuteScriptAsync(checkJs);
//MessageBox.Show(res);
if (res == "true")
{
MessageBox.Show("Please login Moody's");
}
else
{
MessageBox.Show("Successful");
webView21.CoreWebView2.Navigate("https://www.moodys.com/search?keyword=Annual%20default%20study%20excel&searchfrom=GS");
webView21.NavigationCompleted += webView21_NavigationCompleted;
}
}
private void webView21_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
var checkfirst = "document.querySelector('.result-details > .result-detail:nth-child(1) a').getAttribute('href')";
var result = webView21.CoreWebView2.ExecuteScriptAsync(checkfirst);
webView21.CoreWebView2.Navigate("http://www.moodys.com/" + result);
}
}
}
But I found that webView21_NavigationCompleted part always run before complete loading the page, and always returns null then I fail to download.
Are there a method to load the js after the page complete loaded?
Thanks to all who try to help me in this problem.
Although the solution is not perfect enough, it can help me to deal with the problem. I use wait time for 10 seconds and start doing the next steps afterwards. And I also use the TAB key to download the necessary documents.
If there are any good solutions you find please tell me, thank you.
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.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
namespace WinFormsApp2
{
public partial class Form1 : Form
{
private static readonly string indexUrl = "http://www.moodys.com";
public Form1()
{
InitializeComponent();
}
private async void Form1_Load(object sender, EventArgs e)
{
await InitializeAsync(webView21);
}
public async Task InitializeAsync(WebView2 webView21)
{
CoreWebView2Environment webView2Environment = null;
await webView21.EnsureCoreWebView2Async(webView2Environment);
}
private void webView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
webView21.CoreWebView2.Navigate(indexUrl);
}
private void webView21_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
string url = webView21.CoreWebView2.Source.ToString();
Console.WriteLine(url);
}
private void button1_Click(object sender, EventArgs e)
{
bool res = IsLogin();
if (res == true)
{
MessageBox.Show("Please login Moody's");
}
else
{
MessageBox.Show("Successful");
webView21.CoreWebView2.Navigate("https://www.moodys.com/search?keyword=Annual%20default%20study%20excel&searchfrom=GS");
int waittime = 10; //wait 10 seconds
int actualwaittime = waittime * 1000;
wait(actualwaittime);
SendKeys.SendWait("{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}");
SendKeys.SendWait("{ENTER}");
}
}
public void wait(int milliseconds)
{
var timer1 = new System.Windows.Forms.Timer();
if (milliseconds == 0 || milliseconds < 0) return;
// Console.WriteLine("start wait timer");
timer1.Interval = milliseconds;
timer1.Enabled = true;
timer1.Start();
timer1.Tick += (s, e) =>
{
timer1.Enabled = false;
timer1.Stop();
// Console.WriteLine("stop wait timer");
};
while (timer1.Enabled)
{
Application.DoEvents();
}
}
private bool IsLogin()
{
var js = #"document.documentElement.innerText.indexOf('Sign In or Register');";
int res = Convert.ToInt32(ExecuteScript(js));
return res >= 1;
}
private string ExecuteScript(string javaScript)
{
var taskAwaiter = webView21.CoreWebView2.ExecuteScriptAsync(javaScript).GetAwaiter();
WaitAsyncTask(5, taskAwaiter);
return taskAwaiter.GetResult();
}
public void WaitAsyncTask(int waitSecond, System.Runtime.CompilerServices.TaskAwaiter<string> activeTask)
{
DateTime WaitStartTime = DateTime.Now;
double secondDiffer = (DateTime.Now - WaitStartTime).TotalSeconds;
while (secondDiffer < waitSecond)
{
secondDiffer = (DateTime.Now - WaitStartTime).TotalSeconds;
Application.DoEvents();
if (activeTask.IsCompleted)
{
break;
}
}
}
}
}

l versC# multithread issue

I cannot get the ui thread to update the ui while the file copy thread is running. My end goal is to have the animation continue to rotate until the large file copy finally completes to let the user know that the program is not frozen. It's a very simple server to server file copy program.
Can someone tell me what I'm doing wrong?
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.Threading;
using System.IO;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ResetProgress()
{
lblStep1.Image = null;
}
private void SetupProgress()
{
lblStep1.Image = global::animation1.Properties.Resources.animation;
}
private void fileCopy()
{
File.Copy("large file source", "large file destination", true);
}
private void Form1_Load(object sender, EventArgs e)
{
lblStep1.Image = global::animation1.Properties.Resources.animation;
}
private async void button1_Click(object sender, EventArgs e)
{
SetupProgress();
await Task.Run(() => fileCopy());
ResetProgress();
}
private void btnStop_Click(object sender, EventArgs e)
{
// unhandled currently
}
}
}
* Original version *
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.Threading;
using System.IO;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Thread workItemsProducerThread;
private Thread workItemsCopyThread;
public Form1()
{
InitializeComponent();
}
private void ResetProgress()
{
lblStep1.Image = null;
}
private void SetupProgress()
{
this.BeginInvoke((MethodInvoker)delegate ()
{
lblStep1.Image = global::animation1.Properties.Resources.animation;
});
}
private void fileCopy()
{
File.Copy("Large file source", "Large file destination", true);
this.BeginInvoke((MethodInvoker)delegate ()
{
MessageBox.Show("Done");
});
}
private void Form1_Load(object sender, EventArgs e)
{
lblStep1.Image = global::animation1.Properties.Resources.animation;
}
private void btnStart_Click(object sender, EventArgs e)
{
this.workItemsProducerThread = new Thread(new ThreadStart(this.SetupProgress));
this.workItemsProducerThread.IsBackground = true;
this.workItemsProducerThread.Start();
this.SetupProgress();
this.workItemsCopyThread = new Thread(new ThreadStart(this.fileCopy));
this.workItemsCopyThread.IsBackground = true;
this.workItemsCopyThread.Start();
while (workItemsCopyThread.IsAlive)
{
Thread.Sleep(1000); // wait
}
MessageBox.Show("Done");
}
private void btnStop_Click(object sender, EventArgs e)
{
if (this.workItemsProducerThread != null)
{
this.workItemsProducerThread.Abort();
lblStep1.Image = global::animation1.Properties.Resources.animation;
}
}
private void btnTest_Click(object sender, EventArgs e)
{
fileCopy();
}
}
}
Don’t sleep in your click handler. That freezes the UI thread. Just let the clock handler exit. In your file copy thread, when the copy is don’t. Use Invoke(or BeginInvoke) to cause the done messagebox to pop up on the UI thread.
Try this oldy style
private void SetupProgress()
{
Invoke((MethodInvoker) delegate
{
lblStep1.Image = global::animation1.Properties.Resources.animation;
});
}
private Thread TDoSomeWork()
{
var t = new Thread(() => DoSomeWork());
t.Start();
return t;
}
TDoSomeWork();

geckofx how do i enable cookies

I'm curious on how to enable cookies in geckofx, so when I restart the app it shows the cookies when I load the app all it shows is null here is the code to the form have a look and I really need help it might be something to do with proxy.
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 Gecko;
using MaterialSkin;
namespace FoxChatBETA
{
public partial class Form1 : MaterialSkin.Controls.MaterialForm
{
public Form1()
{
InitializeComponent();
var materialSkinManager = MaterialSkinManager.Instance;
materialSkinManager.AddFormToManage(this);
materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
materialSkinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
Xpcom.Initialize(Environment.CurrentDirectory);
GeckoPreferences.User["plugin.state.flash"] = true;
GeckoPreferences.User["network.cookie.thirdparty.sessionOnly"] = true;
GeckoPreferences.User["browser.xul.error_pages.enabled"] = true;
GeckoPreferences.User["media.navigator.enabled"] = true;
GeckoPreferences.User["media.navigator.permission.disabled"] = true;
GeckoPreferences.User["browser.cache.disk.enable"] = true;
GeckoPreferences.User["places.history.enabled"] = false;
GeckoPreferences.Default["extensions.blocklist.enabled"] = false;
}
private void Form1_Load(object sender, EventArgs e)
{
geckoWebBrowser1.Navigate(prefer not to show);
}
private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
{
geckoWebBrowser1.Reload();
}
private void custemnumberToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void reloadToolStripMenuItem_Click_1(object sender, EventArgs e)
{
geckoWebBrowser1.Navigate(pfere not to show again);
}
private void devToolsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void cONFIGToolStripMenuItem_Click(object sender, EventArgs e)
{
geckoWebBrowser1.Navigate("about:config");
}
}
}
You have set network.cookie.thirdparty.sessionOnly to true, which according to the documenation makes them only for the current session. The default value is false.
Third-party cookies are allowed within the limits of the general cookie acceptance settings but only retained for the current session.
https://developer.mozilla.org/pl/docs/Cookies_Preferences_in_Mozilla

how to handle multiple events on forms in c#

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

How can I multithread (effectively) on Windows Forms?

This one is giving me a hard time.
The thing is that I have a code that plays some notes in MIDI, and I wanted to be able to pause it, so I made a simple Form like this:
namespace Music
{
public partial class Form1 : Form
{
static BackgroundWorker _bw = new BackgroundWorker
{
WorkerSupportsCancellation = true
};
private void button1_Click(object sender, EventArgs e)
{
if (!Playing)
{
Playing = true;
_bw.DoWork += Start_Playing;
_bw.RunWorkerAsync("Hello to worker");
}
else
{
Playing = false;
_bw.CancelAsync();
}
}
static void Start_Playing(object sender, DoWorkEventArgs e)
{
//Plays some music
}
}
}
And when I click it starts playing, but no matter what I do, it can't stop. But the thing is that if I do the same thing in the console it works perfect.
Did I miss something?
How can I control a separate thread from the form?
This seems to work...
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.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private BackgroundWorker _bw = new BackgroundWorker { WorkerSupportsCancellation = true,
WorkerReportsProgress = true};
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (_bw.IsBusy)
{
_bw.CancelAsync();
}
else
{
_bw.ProgressChanged += new ProgressChangedEventHandler(_bw_ProgressChanged);
_bw.DoWork += new DoWorkEventHandler(_bw_DoWork);
_bw.RunWorkerAsync();
}
}
void _bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
textBox1.Text += (string)e.UserState;
}
void _bw_DoWork(object sender, DoWorkEventArgs e)
{
int count = 0;
while (!_bw.CancellationPending)
{
_bw.ReportProgress(0, string.Format("worker working {0}", count));
++count;
Thread.Sleep(2000);
}
}
}
}

Categories