I have a problem I made a new form, with background img, and all I need and its working like I wanted, but I also need to auto close it after 5 or 10 seconds.
I searched on google all day ... but no tutorial was good.
I use Visual Studio 2013.
Can you boys help me please...
I'm desperate right now... its almost 10 hours since I'm trying.
You are my last hope.
Thanks
this.close() dosen't did it, or I made it wrong but i doubt that.
Application.Exit fail
timers give errors...
//form
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 Cerum_HS
{
public partial class CERUM_HS : Form
{
public CERUM_HS()
{
InitializeComponent();
Rectangle r = Screen.PrimaryScreen.WorkingArea;
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, Screen.PrimaryScreen.WorkingArea.Height - this.Height);
}
}
}
//main.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
//using System.Windows.Forms;
namespace Cerum_HS
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
private static System.Timers.Timer aTimer;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CERUM_HS());
aTimer = new System.Timers.Timer();
aTimer.Interval = 10;
aTimer = new System.Timers.Timer(10);
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = false;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
//Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
Application.Exit();
//this.close();
}
}
}
Since my comment seemed to help, I thought I write it down as an answer.
public partial class CERUM_HS :
{
// here is the timer for the automatic closing
private static System.Timers.Timer aTimer;
public CERUM_HS()
{
InitializeComponent();
Rectangle r = Screen.PrimaryScreen.WorkingArea;
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, Screen.PrimaryScreen.WorkingArea.Height - this.Height);
}
private void Form_Load(object sender, System.EventArgs e)
{
// start here the timer when the form is loaded
aTimer = new System.Timers.Timer();
aTimer.Interval = 10;
aTimer = new System.Timers.Timer(10);
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = false;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
// Close the Application when this event is fired
Application.Exit();
}
}
Bogdan please comment if this implementation is how it worked for you in the end.
I would put a PictureBox and timer on your form (set to 5000 ms), click on the Tick event, and use this code:
namespace Image
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// set picture box to image of interest
// size and position form appropriately
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
this.Close();
}
}
}
Related
I'm trying to implement a fade in/out to main form open/close, open fade in works fine, however close fade out requires 2 button clicks to work.
Current 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.IO;
using System.Diagnostics;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace DEMO
{
public partial class MainForm : Form
// fade in timer set
System.Windows.Forms.Timer t1 = new System.Windows.Forms.Timer();
System.Windows.Forms.Timer t2 = new System.Windows.Forms.Timer();
private void Form_Load(object sender, EventArgs e)
{
//fade in function
Opacity = 0;
t1.Interval = 10;
t1.Tick += new EventHandler(fadeIn);
t1.Start();
}
// fade in
void fadeIn(object sender, EventArgs e)
{
if (Opacity >= 1)
t1.Stop();
else
Opacity += 0.05;
}
// fade out
void fadeOut(object sender, EventArgs e)
{
if (Opacity <= 0)
{
t2.Stop();
Close();
}
else
Opacity -= 0.15;
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
e.Cancel = true;
t2.Tick += new EventHandler(fadeOut);
t2.Start();
if (Opacity <= 0)
e.Cancel = false;
}
private void customImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I first tried to make it like the button to do the tick start with the e.Cancel but changing the EventArgs e to FormClosingEventArgs e only gave the error: No overload for 'customImageButton1_Click' matches delegate 'System.EventHandler' on which I couldn't find a solution
I am wondering how to constantly update an readonly textbox.
The text box displays a text that always changes.
My problem is if I create an loop the application won't start and if I start the loop using a button my application freezes and only it only runs the loop.
I also can't use a new thread or the thread that I use to change the variables that are displayed within the text because in this case I just get an error System.InvalidOperationException
I was searching for anwser but I couldn't find one.
When using a thread you have to cause your ui update work to run on the UI thread, and that's where you use an "invoke".
There are many ways to achieve your goal, I'll show you two ways you can do it:
using a thread (BackgroundWorker is just a fancier way to do that)
a Timer (it might be overkill to use a thread just to update a
counter if that is what you are intending).
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 WindowsFormsApp2
{
public partial class Form1 : Form
{
bool m_shutdown = false;
int m_counter = 0;
Timer m_timer = new Timer();
BackgroundWorker m_backgroundworker = new BackgroundWorker();
bool m_usetimerway = false; // change this to true to try the timer way
Action m_actionupdatecounter;
public Form1()
{
InitializeComponent();
m_actionupdatecounter = new Action(() =>
{
UpdateCounter();
});
}
private void Form1_Load(object sender, EventArgs e)
{
if (m_usetimerway)
{
m_timer.Interval = 50;
m_timer.Tick += M_timer_Tick;
m_timer.Enabled = true;
}
else
{
m_backgroundworker.DoWork += M_backgroundworker_DoWork;
m_backgroundworker.RunWorkerCompleted += M_backgroundworker_RunWorkerCompleted;
m_backgroundworker.RunWorkerAsync();
}
}
void UpdateCounter()
{
if (this.InvokeRequired)
{
// Get it to be run on the UI thread
this.BeginInvoke( m_actionupdatecounter );
}
else
{
m_counter++;
textBoxCounter.Text = string.Format("{0}", m_counter);
}
}
private void M_timer_Tick(object sender, EventArgs e)
{
// This is already on the UI thread because it's a "WinForms" timer
UpdateCounter();
}
private void M_backgroundworker_DoWork(object sender, DoWorkEventArgs e)
{
while (!m_shutdown)
{
UpdateCounter();
System.Threading.Thread.Sleep(50);
}
}
private void M_backgroundworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
m_shutdown = true;
// To have a more graceful shutdown, you might want to wait for the
// background worker to have "completed" before you actually exit
// your winforms app.
}
}
}
I'm trying to make a function run every 200 milliseconds so that it can show the time difference between when the program first started and right now. I tried threading with this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ComputerTimer
{
public partial class MainWindow : Window
{
private DateTime startTime, endTime;
private static System.Timers.Timer timer1;
private bool running = true;
public MainWindow()
{
InitializeComponent();
startTime = DateTime.Now;
//makes new timer with 200 milliseconds interval
timer1 = new System.Timers.Timer(200);
timer1.Elapsed += new ElapsedEventHandler(timer1_Tick);
timer1.Interval = 200;
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
while (running)
{
endTime = DateTime.Now;
TimeSpan span = endTime - startTime; //gets difference between now and when the program was started
Title.Content = span.ToString().Substring(0, 8); //gets first 8 characters (taking out milliseconds)
}
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
//when button is pressed to stop timer
running = false;
}
}
}
But this just throws the exception 'InvalidOperationException' and says "Additional information: The calling thread cannot access this object because a different thread owns it." about line 48
Title.Content = span.ToString().Substring(0, 8); //gets first 8 characters (taking out milliseconds)
I'm quite confused what to do from here and have searched all over stack overflow looking for an answer but nothing seems to work. I have also tried DispatcherTimer but with no luck.
Edit: This is the answer which worked for me for anyone looking over this in the future
namespace ComputerTimer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private DateTime startTime, endTime;
private DispatcherTimer dtClockTime;
public MainWindow()
{
InitializeComponent();
startTime = DateTime.Now;
dtClockTime = new DispatcherTimer();
dtClockTime.Interval = new TimeSpan(0, 0, 0, 0, 200); //in days, Hour, Minutes, Seconds, millis
dtClockTime.Tick += dtClockTime_Tick;
dtClockTime.Start();
}
private void dtClockTime_Tick(object sender, EventArgs e)
{
endTime = DateTime.Now;
TimeSpan span = endTime - startTime; //gets difference between now and when the program was started
Title.Content = span.ToString().Substring(0, 8);
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
//when button is pressed to stop timer
dtClockTime.Stop();
}
}
}
You've created an endless loop in the timer Tick event, you shouldnt have a while(x) loop in there.
private void timer1_Tick(object sender, EventArgs e)
{
endTime = DateTime.Now;
TimeSpan span = endTime - startTime; //gets difference between now and when the program was started
Title.Content = span.ToString().Substring(0, 8); //gets first 8 characters (taking out milliseconds)
}
And your stop button should just disable the timer
private void btnStop_Click(object sender, RoutedEventArgs e)
{
timer1.Enabled = false;
}
Edit: It might be that you need to set the SynchronisingObject of the timer
timer1.SynchronisingObject = this;
Failing the above it looks like for a wpf application (sorry, I initially missed the wpf tag) you should be using a DispatcherTimer in place of System.Timers.Timer.
The setup is much the same as your existing code, it just uses a different type of timer which raises the tick event on the correct (UI) thread.
As an aside, there is no need to string mash a DateTime object, there are methods for being able to format a timespan
Title.Content = span.ToString("mm:ss.ffff");
Only add SynchronisingObject parameter for your timer.
Like this:
timer1.SynchronisingObject = this;
I'm new to c# and Multithreading. I have this code to getting started with Multithreading but clock tick isn't getting started. What's wrong with this code? No error occurs because its a logical error I guess. Any help would be appreciated.
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 Implementing_Databases
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
picturebox1.Location=new Point(0,20);
pictureBox2.Location = new Point(0, 60);
}
int B1 = 0;
int B2 = 0;
private void Form1_Load(object sender, EventArgs e)
{
Thread Th1 = new Thread(Go1);
Thread Th2 = new Thread(Go2);
Th1.Start();
Th2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
picturebox1.Left = B1;
B1 += 5;
}
private void timer2_Tick(object sender, EventArgs e)
{
pictureBox2.Left = B2;
B2 += 5;
}
void Go1()
{
timer1.Start();
}
void Go2()
{
timer2.Start();
}
}
}
First of all, try declaring threads as properties of form rather than declaring them as local function variables. Because otherwise they may be collected by GC straight away after Load handler exits.
Secondly, UI not updating may be due to the fact that you cannot update UI data from non GUI thread. See InvokeRequired/Invoke feature of WinForms programming. See https://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired(v=vs.110).aspx for more details
I'm working on a c# project with WPF but I've a problem and this makes me crazy :)
Here is the problem. I'm trying to change new window's opacity with timer. But when I run the project, "this.Opacity += .1;" code throws an exception like "Invalid operation etc..."
I'm opening a window from MainWindow.cs file with this code:
private void MenuItemArchiveClick(object sender, RoutedEventArgs e)
{
var archiveWindow = new ArchiveWindow();
var screenSize = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
archiveWindow.Width = (screenSize.Width * 95) / 100;
archiveWindow.Height = (screenSize.Height * 90) / 100;
archiveWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
archiveWindow.Margin = new Thickness(0, 10, 0, 0);
archiveWindow.AllowsTransparency = true;
archiveWindow.Opacity = 0.1;
archiveWindow.Topmost = true;
archiveWindow.Show();
}
My ArchiveWindow code is,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace POCentury
{
/// <summary>
/// Interaction logic for ArchiveWindow.xaml
/// </summary>
public partial class ArchiveWindow : Window
{
Timer timer1 = new Timer();
public ArchiveWindow()
{
InitializeComponent();
timer1.Interval = 1 * 1000;
timer1.Elapsed += new ElapsedEventHandler(opacityChange);
timer1.Enabled = true;
timer1.AutoReset = false;
timer1.Start();
}
private void opacityChange(object sender, EventArgs a)
{
if (this.Opacity == 1)
{
timer1.Stop();
}
else
{
this.Opacity += .1;
}
}
private void ArchiveWindowClose()
{
timer1.Stop();
this.Close();
}
private void btnArchiveWindowClose(object sender, RoutedEventArgs e)
{
ArchiveWindowClose();
}
private void imgPatternClick(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("sd");
}
}
}
Can you help me with doing that?
Thank you so much!
Basically, you can't access the timer inside the opacityChange event because it's happening in a different thread. You need the Dispatcher to do that.
Dispatcher.BeginInvoke(new Action(() =>
{
if (this.Opacity == 1)
{
timer1.Stop();
}
else
{
this.Opacity += .1;
}
}));