I am working on a wpf application. Here I need to use System.Windows.Forms.FolderBrowserDialog in my Wpf application.
System.Windows.Forms.FolderBrowserDialog openFolderBrowser = new System.Windows.Forms.FolderBrowserDialog();
openFolderBrowser.Description = "Select Resource Path:";
openFolderBrowser.RootFolder = Environment.SpecialFolder.MyComputer;
if (openFolderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//some logic
openFolderBrowser.Dispose();
}
I launch a FolderBrowserDialog, select a Folder and click OK, and then I launch another System.Windows.Forms.FolderBrowserDialog, My problem is when I select a Folder and click OK in this FolderBrowserDialog, the shadow of FolderBrowserDialog remains on the screen(means my screen doesn't refresh). I need to minimize or resize it in order to remove the shadow of FolderBrowserDialog. How can I solve this issue?
Any help plz?
Edit:
I found the solution. I called OnRender method on my wpf Window and it worked for me. It redraws everythign on the screen.
You can call InvalidateVisual method to refresh UI.
on a form code
Update();
refreshes screen and updates ui.
We are using winforms so Update() is a basic function that redraws the window content. so you may use it directly from a form. The basic usage could be a timer which updates a label on a screen. when timer ticks you update the label:
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 1000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
void timer_Tick(object sender, EventArgs e)
{
label1.text = DateTime.Now.ToString("h:mm:ss"));
Update(); //this will refresh the form and label's text is updated.
}
otherwise label1.text will never change.
Related
My goal is to make a desktop pet. I've already programmed a lot of logic that executes in a while loop and updates every iteration. To display the creature I'm looking to use windows forms, but that has brought up a dilemma.
I want to be able to execute the logic, and then update the window in the same loop (process events and redraw), without having to deal with Application.Run() or multi threading. As an example, and as someone who's come from python, using tkinter it's possible to call the update() method on a window in a loop, which is essentially the same as calling mainloop() once, except it doesn't block the program.
Do forms offer any similar functionality?
As Scott Chamberlain mentioned, you should use a timer to run your 'loop'. Winforms is event based so adding an infinite loop will freeze the program since events are blocked.
This code illustrates how to use a timer. I added a picture box to the form and it moves across the screen as the timer fires.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Timer tmr = new Timer();
tmr.Interval = 50; // milliseconds
tmr.Tick += Tmr_Tick; // set handler
tmr.Start();
}
private void Tmr_Tick(object sender, EventArgs e) //run this logic each timer tick
{
pictureBox1.Left += 1; // move image across screen, picture box is control so no repaint needed
}
}
I am trying to create a windows form that gets displayed for 2 seconds when triggerd by an event, and then closes automatically.
I have tried several options. This is my current code:
this.aletPopup.StartPosition = FormStartPosition.CenterScreen;
this.aletPopup.Show();
Thread.Sleep(2000);
this.aletPopup.Close();
This preforms the actions that I desire, however, when the form loads it does not load the label or image which is on the form. Instead, the area where the image and label are become transparent. My desired output is this:
I have also tried using this.aletPopup.ShowDialog();, which does display the graphics. However, the form will not close automatically when using this method.
EDIT: I am attempting to use
Michael Perrenoud's solution. However, I cannot get the form to close. I have a timer set at a 2000ms interval which is initally disabled. Am I overriding the OnShown correctly?
public AlertPopForm()
{
InitializeComponent();
}
private void closingTimer_Tick(object sender, EventArgs e)
{
closingTimer.Enabled = false;
this.Close();
}
private void AlertPopForm_OnShown(object sender, System.EventArgs e)
{
closingTimer.Enabled = true;
closingTimer.Start();
}
Instead, how about leveraging ShowDialog, and then using a Timer on the dialog form. In the Tick event of the Timer, close the form.
this.aletPopup.StartPosition = FormStartPosition.CenterScreen;
this.aletPopup.ShowDialog();
You could even pass the interval into the .ctor of the dialog form if you wanted some flexibility.
It's very important to note here that you'd need to leverage the OnShown override to actually Start the Timer so the form is in fact shown to the user.
The reason can be in Message Loop. When you block your thread by Thread.Sleep, it also blocks Message loop.
You can make like this:
this.aletPopup.StartPosition = FormStartPosition.CenterScreen;
this.aletPopup.Show();
for(var i = 0; i<= 200; i++)
{
Thread.Sleep(10);
Application.DoEvents();
}
this.aletPopup.Close();
DoEvents will process messages from message queue during that time.
When calling Thread.Sleep you're blocking the UI thread, thus preventing it from processing UI events.
You need to ensure that Close is called after 2 seconds without actually blocking the main thread. There are a number of ways of doing this, such as using a Timer, or something like Task.Delay:
aletPopup.StartPosition = FormStartPosition.CenterScreen;
aletPopup.Show();
Task.Delay(TimeSpan.FromSeconds(2))
.ContinueWith(t => aletPopup.Close(),
TaskScheduler.FromCurrentSynchronizationContext());
The reason this is happening, is that you are halting the thread that draws the form. So the form has time to display, but as it's being drawn, the thread is being stopped.
Easy enough to fix....
Add an event handler to the popup for the Load event with the following handler:
private async void handleLoad(Object sender, EventArgs args)
{
await Task.Delay(2000);
Close();
}
Remark
Because you used Show(), the user could always click around this popup. If this is undesirable, then use ShowDialog() instead.
Did you try a refresh to redraw the form?
this.aletPopup.StartPosition = FormStartPosition.CenterScreen;
this.aletPopup.Show();
this.alertPopup.Refresh();
Thread.Sleep(2000);
this.aletPopup.Close();
I have 2 WinForms
Form2 uses Infragistics ultraTabControl.
On Tab Changing im Showing Form1.
In Form1
I have a PictureBox assigned with animated GIF
In Form2
I am displaying Form1 like this.
Form1 frmOne=new Form1();
frmOne.Show();
Problem
GIF is not playing animation.
Make sure you have your image in the image property NOT THE BACKGROUND IMAGE PROPERTY. That's the mistake I made
It is working fine for me. I have just dragged a new pictureBox on form and setting image property at Form_Load() event and showing GIF animated.
I did same as you on button click:
TestForms.NavBarTest newForm = new TestForms.NavBarTest();
newForm.Show();
At my Test Form:
private void NavBarTest_Load(object sender, EventArgs e)
{
pictureBox1.Image = NavronChartControl.Properties.Resources.url;
}
Note: If your picture box is disabled then it will not animate the Gif
Reference:
How do you show animated GIFs on a Windows Form (c#)
Animated Progress Indicator in C# (Windows Forms)
Try to implement using this link:Animated GIF in picturebox won't animate apprach.
The best way to achieve it is to run the animation in an async task, but accordingly, some limitations are possible to do that on windows form using:
System.Threading.Thread.Sleep(int milliseconds).
My splash view is displayed with a gif (loading)
e.g.: In your constructor,
public partial class MainMenu : Form
{
private SplashScreen splash = new SplashScreen();
public MainMenu ()
{
InitializeComponent();
Task.Factory.StartNew(() => {
splash.ShowDialog();
});
Thread.Sleep(2000);
}
It is imperative to put the Thread.Sleep(int) after starting a new one, don't forget that every action you did on this thread needs to be invoked, for example:
void CloseSplash()
{
Invoke(new MethodInvoker(() =>
{
splash.Close();
}));
}
Now your gif should work!
Solved
My current Thread is busy to Play GIF Animation.
I tried So many ways like Application.DoEvents(); etc.
But every thing can't helped me.
The answer in the following Question, which uses Threading is a very great working idea.
StackOverFlow: Show/Hide Splash Screen
Thanks for every one.
This question has already raised before.
Though the approach is different but the questions concept is the same
StackOverFlow: How do you show animated GIFs on a Windows Form (c#)
Source project where you can use Code Project
I guess that will help you out
I had the same issue and came across different solutions by implementing which I used to face several different issues. Finally, below is what I put some pieces from different posts together which worked for me as expected.
private void btnCompare_Click(object sender, EventArgs e)
{
ThreadStart threadStart = new ThreadStart(Execution);
Thread thread = new Thread(threadStart);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
Here is the Execution method that also carries invoking the PictureBox control:
private void Execution()
{
btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = true; });
Application.DoEvents();
// Your main code comes here . . .
btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = false; });
}
Keep in mind, the PictureBox is invisible from Properties Window or do below:
private void ComparerForm_Load(object sender, EventArgs e)
{
pictureBox1.Visible = false;
}
If none of the previous answers work for you, another idea is to refresh the image tag or write it on the fly with jQuery.
In my case I needed to show an animated GIF when a button on the form was clicked. Previously it would show up but not animate. I just added a jQuery event when the button was clicked that added the image tag on-the-fly to a div through the parent tag's html() function.
$('.showhidegif').html("<img src='/Content/img/angled-spinner.gif' />");
<div class="col-sm-12 showhidegif"></div>
Worth a shot especially if you're already using jquery on your page.
I work on C# .I want to create a Desktop(not web) application in c#.There i need to popup window like as web.When popup window appear user can not access any control like web loading panel property MODEL=true.My application work flow is:
Popup appear
Event Start
Event Complete
Popup close
Then Perform rest of the application
private void timer1_Tick(object sender, EventArgs e)
{
if (progressBar1.Value >= 200)
{
progressBar1.Value = 0;
GetAllData();//When this Method active .Progress bar show it's //progressing.After complete the work progressbar will hide.How can i measure how much //time does the computer needs to complete this method work.
timer1.Stop();
}
progressBar1.Value += 20;
}
Assuming your popup is a form you can use ShowDialog instead of Show to make the form modal.
I think you are talkin about modal dialog boxes. If you using WPF, read this:
http://msdn.microsoft.com/en-us/library/aa969773.aspx
I'm running a data import, using a Windows form to kick off the import and show progress.
I've got this whole thing so nice and user friendly, with major and minor progress bars and everything... but just one problem... the form refresh keeps going AWOL.
I have a call to Form.Refresh() every time I update my labels/progress bars, and it usually starts off working. But if ever I need to break into debug mode, just to hand-hold the import a bit, the Refresh() call stops working, and sometimes even if I'm running without Debug mode, at some unpredictable point the same thing happens: the labels and progress bars do not get updated, and if you hide the form and reopen it, the form does not repaint at all - it just shows up entirely white.
Why, oh why, does Form.Refresh() stop working, and how can I fix this?
It sounds as if the import runs on the UI thread, which means that this thread is blocked, preventing the form from repainting itself. A better approach would be to use a BackgroundWorker component, do the import in the DoWork event handler and use the ProgressChanged to update the UI.
Example:
private void StartImport()
{
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.RunWorkerAsync();
}
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// do some work simulating a lenghy process which occasionally
// reports progress with data back to the caller
for (int i = 0; i < 100; i++)
{
Thread.Sleep(200);
backgroundWorker.ReportProgress(i, "Item No " + i.ToString());
}
}
private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
listBox.Items.Add(e.UserState.ToString());
}
Using this approach you will typically not need to call Refresh to force a repaint of the form.
You may want to change your code into using BeginUpdate and EndUpdate, like so:
Control.BeginUpdate();
// Do something to the control, e.g. add items or whatnot
Control.EndUpdate();
This way Refresh shouldn't be necessary.
AFAIK constantly calling Refresh is really a hack and should be avoiding, as it stresses the CPU quite a bit (it has to refresh everything instead of just the things which are changed).
Edit: If the form starts being white, it seems the drawing code is not been called at all, which indicates it's somewhat not responding.
I'd check the code for anything that can deadlock or otherwisely hang.
You could use observer pattern..in short if anything changes in model observer pattern will make sure that change is visible on form..
google it for some examples..
Depending on what .NET framework you're using, you can use the Task.Run approach:
private void btnShowProgress_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
Task.Run(() =>
{
for (int i = 0; i <= 100; i++)
{
Thread.Sleep(100);
progressBar1.Invoke(new MethodInvoker(delegate { progressBar1.Value = i; }));
}
});
}
Task.Run info
Using invoke with controls
The solution may not be the best practice but it definitely works for small applications.
In Form1 create a bool to check to see if the form is closed.
public bool formclosed = false
Then in Form2 on the Form Closing Event Handler add
formclosed = true
also in the Form2 after
InitializeComponent();
add
formclosed = false;
In Form1 create a timer.
In the timer1.Tick event handler say
private void timer1_Tick(object sender, EventArgs e)
{
if(formclosed == true)
{
Application.Restart();
}
}
This will restart the application and refresh everything ... I also had my text saved to the Properties.Settings.Default so everytime the application started the default settings would show.
I created an initial version of a Progress control using a BackgroundWorker. The Progress control computed and displayed nice things like Estimated Duration, Estimated Time to Completion. Each statistic was displayed by custom control based on a Label control. The Progress control worked in my production code.
Then I made some changes to the Progress control. I switched from basing my custom statistics controls from Label to Panel. I successfully ran all my tests (using NUnit). Then, I created a Test Windows Forms app. The Progress control successfully worked in the Test Windows Forms app.
When I ran my production Windows app with the updated Progress control it didn't display the statistics.
I tried Thread.Sleep(N), Form.Refresh(). None of those worked to update the statistics.
I eventually called Control.Invalidate() on each Statistic control. The Invalidate caused OnPaint to be called and the control happily updated the display with its specific statistic.
For Each Stat_Obj As Control in Statistics_Controls
Stat_Obj.Invalidate()
Next
You might need to give the window time to redraw itself. I understand you're doing the import in a loop and the loop is running on the main UI thread? Try adding this line to the loop:
Application.DoEvents();