Reputation: 1205
In this i am using stopwatch. when stop watch value between 0 to 15 it will play video on screen 1 and after 15 it will display on screen 0 but thread is not starting after Thread.sleep()
public partial class Form2 : Form
{
int[] screentimings = new int[2] { 20, 20 };
Stopwatch sp;
Thread thread1;
//private System.Timers.Timer _timer = new System.Timers.Timer();
public Form2()
{
InitializeComponent();
thread1 = new Thread(new ThreadStart(A));
thread1.SetApartmentState(ApartmentState.STA);
sp = new Stopwatch();
sp.Start();
thread1.Start();
}
[STAThread]
public void showOnMonitor(int showOnMonitor)
{
Screen[] sc;
sc = Screen.AllScreens;
Form1 f = new Form1();
f.FormBorderStyle = FormBorderStyle.None;
f.Left = sc[showOnMonitor].Bounds.Left;
f.Top = sc[showOnMonitor].Bounds.Top;
f.Height=sc[showOnMonitor].Bounds.Height;
f.Width=sc[showOnMonitor].Bounds.Width;
f.StartPosition = FormStartPosition.Manual;
f.ShowDialog();
}
[STAThread]
private void A()
{
long i = sp.Elapsed.Seconds;
if (i > 0 && i < 15)
{
showOnMonitor(1);
}
else
{
showOnMonitor(0);
}
Thread.Sleep(500);
}
}
showOnMonitor(1) code is executed but after 15 seconds showOnMonitor(0) is not working.
I am new with thread don't know whats wrong with it. It might be because of [STAThread]
without this it giving Single Thread Exception.
Upvotes: 0
Views: 116
Reputation: 73502
You don't need a thread at all. Threads are used to do more than one action concurrently. Explaining it will be out of scope of this question. Please read more about threads here.
Since you're in .Net 4.5 you can use async/await to accomplish your goal very easily.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
protected async override void OnLoad(EventArgs e)
{
base.OnLoad(e);
await ShowForms();//Show the forms
}
private async Task ShowForms()
{
ShowOnMonitor(1);
await Task.Delay(15000);//15 seconds, adjust it for your needs.
ShowOnMonitor(2);
}
private void ShowOnMonitor(int showOnMonitor)
{
Screen[] allScreens = Screen.AllScreens;
Rectangle screenBounds = allScreens[showOnMonitor - 1].Bounds;
Form1 f = new Form1
{
FormBorderStyle = FormBorderStyle.None,
Left = screenBounds.Left,
Top = screenBounds.Top,
Height = screenBounds.Height,
Width = screenBounds.Width,
StartPosition = FormStartPosition.Manual
};
f.Show();//Use show, not ShowDialog.
}
}
Upvotes: 2