I'm having this issue for a while now on some machines, when the user runs the application all the buttons, images, menu items, almost everything goes blank.
My first thought was: I have a separate thread using BackgroundWorker updating a StatusBar and I've read that this can cause issues to form rendering.
I found an article (it's in portuguese, since I'm a Brazilian) that explains this is a issue caused by a security plugin installed by our banks called Warsaw. One of the solutions was to contact the developers to have them analyze your software so the plugin will work correctly. I've done this and I'm waiting for their response.
The other solution is to sign our assembiles so the plugin may recognize as a trusted software, this is good but not free of charge unfortunately.
Now, here's an example of my application looks like when it's launched with this issue:
A form with a GridView
The code for the separate thread as mentioned above:
int countAlerta = 0;
int countAlertaRFRP = 0;
int countAlertaAditivo = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
backgroundWorker1.RunWorkerAsync();
else
{
alertaToolStripStatusLabel.Text = "Continuando a verificação...";
alertaToolStripStatusLabel.IsLink = false;
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(0);
timer1.Enabled = false;
lock (new object())
{
countAlerta = new BLL.AlertasBLL().CountRVSRAS();
countAlertaRFRP = new BLL.AlertasBLL().CountRFRP();
countAlertaAditivo = new BLL.AlertasBLL().CountAditivos();
}
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
alertaToolStripStatusLabel.Text = "Verificando...";
alertaToolStripStatusLabel.IsLink = false;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (countAlerta + countAlertaAditivo + countAlertaRFRP > 0)
{
alertaToolStripStatusLabel.Text = "ALERTA: Verifique!!!";
alertaToolStripStatusLabel.IsLink = true;
alertaToolStripStatusLabel.Font = new Font(alertaToolStripStatusLabel.Font, FontStyle.Bold);
}
else
{
alertaToolStripStatusLabel.Text = "Não existem alertas";
alertaToolStripStatusLabel.IsLink = false;
}
timer1.Enabled = true;
}
Related
I'm trying to save a rather large text file when the user hits the save button. It can be up to 30MBs. After pressing the button, I'd like the texbox to display "Saving..." as it's saving the file and when it completes, display "Saved". However I can't get this to work. I've tried using Task.run, await task.Run, and using a background worker. All these options hang the UI until the save completes. The textbox does not display "Saving..." until after it saves and the program is unresponsive until then. How can I fix this?
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.ShowDialog();
// If the file name is not an empty string open it for saving.
if (saveFileDialog1.FileName != "")
{
logFileName = saveFileDialog1.FileName;
btnOpenFile.IsEnabled = false;
btnSave.IsEnabled = false;
tbText1.Text += "\n\n***Saving...***\n";
tbText1.ScrollToEnd();
await Task.Run(() => File.WriteAllText(logFileName, Results.ToString()));
tbText1.Text += "\n\n***SAVED***\n\n";
tbText1.ScrollToEnd();
btnOpenFile.IsEnabled = true;
btnSave.IsEnabled = true;
}
As discussed in the comments, the problem is with Results.ToString().
I tried to reproduce the issue with this code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
for (int i = 1; i < 40536; i++)
{
stringBuilder.Append(new string('a', i));
}
}
readonly StringBuilder stringBuilder = new StringBuilder();
int tickNumber = 0;
private void sync_Click(object sender, EventArgs e)
{
button1.Enabled = false;
stringBuilder.ToString();
button1.Enabled = true;
}
private async void async_Click(object sender, EventArgs e)
{
button2.Enabled = false;
await Task.Run(() => stringBuilder.ToString());
button2.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
tickNumber %= 50;
tickNumber++;
label1.Text = new string('.', tickNumber);
}
}
But it works as expected:
Sometimes UI hands for a little bit though. Is this what are you talking about?
Try moving code that generates contents for StringBuilder inside the task (so this StringBuilder only exists in background thread)
I am trying to create a application with multiple forms,
I have placed the forms on top of each other in the section needed.
However, the code as provided does not work.
private void home_butt_Click(object sender, EventArgs e)
{
Home_Panel.Visible = true;
Home_Panel.BringToFront();
}
private void Intro_butt_Click(object sender, EventArgs e)
{
Introduction.Visible = true;
Introduction.BringToFront();
Home_Panel.Visible = false;
Crime.Visible = false;
}
private void Crime_butt_Click(object sender, EventArgs e)
{
Crime.Visible = true;
Crime.BringToFront();
Home_Panel.Visible = false;
Introduction.Visible = false;
}
It will the home_Panel on start up but when you click on a button it will only show the Crimes Panel.
Any help will be appreciated.
Why not use the show and hide methods for forms instead of bringing them to the front and setting the visibility? E.G.
private void home_butt_Click(object sender, EventArgs e)
{
Home_Panel.Show();
Crime.Hide();
Introduction.Hide();
}
And vice versa for the other button events?
I've looked in many places for this but still haven't found a solution. What I'm trying to achieve is being able to use BackgroundWorker on a timed basis. Here's an example:
public Main()
{
isDbAvail = new BackgroundWorker();
isDbAvail.DoWork += isOnline;
isDbAvail.RunWorkerCompleted += rewriteOnlineStatus;
}
private void rewriteOnlineStatus(object sender, RunWorkerCompletedEventArgs e)
{
Subs.Connection connection = new Subs.Connection();
changeStatus(connection.isDbAvail());
}
private void isOnline(object sender, DoWorkEventArgs e)
{
while (true)
{
Console.WriteLine("Checking database connection");
System.Threading.Thread.Sleep(8000);
}
}
public void changeStatus(bool status)
{
if (status)
{
serverStatusVal.Text = "Connected";
serverStatusVal.ForeColor = System.Drawing.Color.DarkGreen;
}
else
{
serverStatusVal.Text = "Not connected";
serverStatusVal.ForeColor = System.Drawing.Color.Red;
}
}
What's happening here is that the isOnline method checks if there is a connection to the database (just an example) every 8 seconds and changes the text accordingly. What I've noticed though, is that the while loop inside the isOnline method causes the rewriteOnlineStatus method never to fire because it runs indefinitely. Is there another workaround to this?
I suggest you use BackgroundWorker.ReportProgress, and check connectivity in the background thread.
Something like this:
public Main()
{
isDbAvail = new BackgroundWorker();
isDbAvail.WorkerReportsProgress = true;
isDbAvail.DoWork += isOnline;
isDbAvail.ProgressChanged += rewriteOnlineStatus;
isDbAvail.RunWorkerAsync();
}
private void rewriteOnlineStatus(object sender, ProgressChangedEventArgs e)
{
changeStatus((bool)e.UserState);
}
private void isOnline(object sender, DoWorkEventArgs e)
{
while (true)
{
Console.WriteLine("Checking database connection");
Subs.Connection connection = new Subs.Connection();
isDbAvail.ReportProgress(0, connection.isDbAvail);
System.Threading.Thread.Sleep(8000);
}
}
Now the BackgroundWorker is doing the work, and reporting back to the UI thread via ProgressChanged.
I've got this annoying problem which I can't track down where it goes wrong.
I'm creating a Windows Media Player in code and I'm trying to loop a video... It loops, but only once...
So it plays the video, and once more. And then it just stop and shows the end of the video. So it seems as if it loops only once.
This is the code I have:
try {
wmPlayer = new AxWMPLib.AxWindowsMediaPlayer();
wmPlayer.enableContextMenu = false;
((System.ComponentModel.ISupportInitialize)(wmPlayer)).BeginInit();
wmPlayer.Name = "wmPlayer";
wmPlayer.Enabled = true;
wmPlayer.Dock = System.Windows.Forms.DockStyle.Fill;
mainForm.Controls.Add(wmPlayer);
((System.ComponentModel.ISupportInitialize)(wmPlayer)).EndInit();
wmPlayer.uiMode = "none";
if(kind == "idle") {
IdleVideo(name);
}
}
catch { }
}
private static void IdleVideo(string name) {
System.Diagnostics.Debug.WriteLine("Video called once");
wmPlayer.URL = #"C:\ProjectSilver\assets\RadarDetectie\idle\" + name + "_idlescreen_movie.ogv";
Debug.WriteLine(wmPlayer.URL);
wmPlayer.settings.setMode("loop", true);
wmPlayer.Ctlcontrols.play();
}
So I hope you guys can help, why doesn't it keep playing?
just use
private void Form1_Load(object sender, EventArgs e)
{
// give the path of your video here
axWindowsMediaPlayer1.URL = "Path of your video";
// this line will automatically start your video
axWindowsMediaPlayer1.settings.autoStart = true;
//here the system will automatially create a thread and will keep on
running your video...
axWindowsMediaPlayer1.settings.setMode("loop", true);
}
Add an event handler for the PlayStateChange event:
wmPlayer.PlayStateChange += wmPlayer_PlayStateChange;
Then in the event handler check if e.newState==8 which means media ended:
AxWMPLib.AxWindowsMediaPlayer wmPlayer;
private void player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if(e.newState==8) // MediaEnded
// call function to play the video again
}
For play states, check this:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd562460%28v=vs.85%29.aspx
Edit:
I don't know what you do with kind, or where the first part of your code is defined, but this worked for me:
AxWMPLib.AxWindowsMediaPlayer wmPlayer;
private void button2_Click(object sender, EventArgs e)
{
wmPlayer = new AxWMPLib.AxWindowsMediaPlayer();
wmPlayer.CreateControl();
wmPlayer.enableContextMenu = false;
((System.ComponentModel.ISupportInitialize)(wmPlayer)).BeginInit();
wmPlayer.Name = "wmPlayer";
wmPlayer.Enabled = true;
wmPlayer.Dock = System.Windows.Forms.DockStyle.Fill;
this.Controls.Add(wmPlayer);
((System.ComponentModel.ISupportInitialize)(wmPlayer)).EndInit();
wmPlayer.uiMode = "none";
wmPlayer.URL = #"C:\...";
wmPlayer.settings.setMode("loop", true);
wmPlayer.Ctlcontrols.play();
}
I have a situation which occurs in WebBrowser with C#.
I am trying to do downloader through a site However , when i click first time, it doesn't work but if I click second times it works.
How can i solve this problem .
Sincerely.
Codes :
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.GetElementById("youtube-url").SetAttribute("value", textBox1.Text);
webBrowser1.Document.GetElementById("submit").InvokeMember("click");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
label3.Text = "Video Alındı , indirme işleminin hazır olması bekleniyor";
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlElementCollection col = webBrowser1.Document.GetElementsByTagName("a");
String link = "";
foreach (HtmlElement el in col)
{
if (el.InnerText == "Download")
{
link = el.GetAttribute("href");
Download(link);
label3.Text = "Video indiriliyor";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate("http://www.youtube-mp3.org/tr");
}
void Download(String link)
{
WebClient downloader = new WebClient();
downloader.DownloadFileAsync(new Uri(link),#"D:\a.mp3");
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);
}
void downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label3.Text = "Video İndiriliyor : " + progressBar1.Value + "%";
if (progressBar1.Value == 100)
label3.Text = "Video İndirildi";
}
You're blocking yourself from investigating what the problem is. It's never a good idea to disable script errors for WebBrowser control (as you do with ScriptErrorsSuppressed = true), unless you handle them internally in your host app. Do the following:
enable script errors (ScriptErrorsSuppressed = false);
enable script debugging for all applications;
implement WebBrowser Feature Control (FEATURE_BROWSER_EMULATION), so the web page is getting the same (or close) experience and HTML features as with full-featured IE browser.
Then, hopefully, you can find out what's going wrong when you're simulating a button click, and debug it.