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;
}
}));
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 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();
}
}
}
What the application should do
This application should take the input of time (seconds, minutes and hours) and shutdown the computer after that time. It should also update the text box with how long left until the computer has shut down.
What the application actually does
I had an issue that I 'fixed' where the called ac across threads weren't safe, so I fixed it and I don't get that error now. However, the updateThread doesn't update and print the time left; and the text box doesn't get "test" appended to it. The UI also becomes Not Responding. Any help would be much appreciated.
Also, if you see anything else that could be done better, please comment and explain. Thanks!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ShutdownPC
{
public partial class Form1 : Form
{
int inputHours;
int inputMinutes;
int inputSeconds;
Thread sleepingThread;
Thread updatingThread;
NotifyIcon shutdownPCIcon;
Icon defaultIcon;
public Form1()
{
InitializeComponent();
defaultIcon = new Icon("defaultIcon.ico");
shutdownPCIcon = new NotifyIcon();
shutdownPCIcon.Icon = defaultIcon;
shutdownPCIcon.Visible = true;
MenuItem progNameMenuItem = new MenuItem("ShutdownPC by Conor");
MenuItem breakMenuItem = new MenuItem("-");
MenuItem quitMenuItem = new MenuItem("Quit");
ContextMenu contextMenu = new ContextMenu();
contextMenu.MenuItems.Add(progNameMenuItem);
contextMenu.MenuItems.Add(breakMenuItem);
contextMenu.MenuItems.Add(quitMenuItem);
shutdownPCIcon.ContextMenu = contextMenu;
shutdownPCIcon.Text = "ShutdownPC";
quitMenuItem.Click += QuitMenuItem_Click;
}
private void QuitMenuItem_Click(object sender, EventArgs e)
{
shutdownPCIcon.Dispose();
sleepingThread.Abort();
updatingThread.Abort();
this.Close();
}
public void sleepThread()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(sleepThread));
}
else {
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
button1.Enabled = false;
int totalMilliseconds = ((inputHours * 3600) + (inputMinutes * 60) + inputSeconds) * 1000;
Thread.Sleep(totalMilliseconds);
//Process.Start("shutdown", "/s /t 0");
richTextBox1.AppendText(String.Format("test"));
}
}
public void updateThread()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(updateThread));
}
else {
int totalSeconds = (inputHours * 3600) + (inputMinutes * 60) + inputSeconds;
while (totalSeconds > 0)
{
TimeSpan time = TimeSpan.FromSeconds(totalSeconds);
string timeOutput = time.ToString(#"hh\:mm\:ss");
richTextBox1.AppendText(String.Format(timeOutput));
Thread.Sleep(1000);
richTextBox1.Clear();
totalSeconds--;
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
inputHours = Convert.ToInt32(textBox1.Text);
inputHours = int.Parse(textBox1.Text);
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
inputMinutes = Convert.ToInt32(textBox2.Text);
inputMinutes = int.Parse(textBox2.Text);
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
inputSeconds = Convert.ToInt32(textBox3.Text);
inputSeconds = int.Parse(textBox3.Text);
}
private void button1_Click(object sender, EventArgs e)
{
updatingThread = new Thread(new ThreadStart(updateThread));
updatingThread.Start();
sleepingThread = new Thread(new ThreadStart(sleepThread));
sleepingThread.Start();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
Using Invoke in the beginning of method that runs in separate thread is bad idea, because all code runs in GUI thread and lock it.
You should Invoke only GUI updating code!!!
I have a windows form application that basically pings an ip and then returns an image with a tooltip that displays the rtt to that ip.
What i want to do is have the the form ping that ip every 20 seconds, so that the form and images change. If i could get that to work then I would like to some how store maybe 4 rtt's and then show an average of the 4 in the tooltip.
So far the form is only pinging once, I've played around with a timer but I don't really know what I am doing. Here is my code so far.
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.Net.NetworkInformation;
using System.ServiceProcess;
using System.Threading;
using System.ComponentModel;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
Ping pingClass = new Ping();
PingReply pingReply = pingClass.Send("10.209.123.123");
label4.Text = (pingReply.RoundtripTime.ToString());
//+ "ms");
label5.Text = (pingReply.Status.ToString());
if (Convert.ToInt32(label4.Text) > 0 && Convert.ToInt32(label4.Text) < 100)
this.pictureBox1.Load("greenLAT.png");
if (Convert.ToInt32(label4.Text) > 100 && Convert.ToInt32(label4.Text) < 200)
this.pictureBox1.Load("yellowLAT.png");
if (Convert.ToInt32(label4.Text) > 200 && Convert.ToInt32(label4.Text) < 1000)
this.pictureBox1.Load("redLAT.png");
ToolTip tt = new ToolTip();
tt.SetToolTip(this.pictureBox1, "Your current network delay is " + label4.Text + "ms");
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
//MessageBox.Show("Timeout!");
Refresh();
}
}
}
Try this:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Net;
using System.Windows.Forms;
using System.Net.NetworkInformation;
namespace DXWindowsApplication4
{
public partial class Form2 : Form
{
private readonly Timer _timer;
private readonly Ping _pingClass;
private readonly IPAddress _ipAddress;
private readonly int _timeout;
private Image _greenImage;
private Image _yellowImage;
private Image _redImage;
private int _pingCount;
private long _avgRtt;
public Form2()
{
InitializeComponent();
IPAddress.TryParse("98.138.253.109", out _ipAddress); // yahoo.com Ip address
_timer = new Timer();
_timeout = 3000;
_pingClass = new Ping();
_pingClass.PingCompleted += PingClassPingCompleted;
}
void PingClassPingCompleted(object sender, PingCompletedEventArgs e)
{
RefreshPing(e.Reply);
}
public void FormLoad(object sender, EventArgs e)
{
_timer.Tick += TimerTick;
_timer.Interval = 4000;
_timer.Start();
}
private void TimerTick(object sender, EventArgs e)
{
_pingClass.SendAsync(_ipAddress, _timeout);
}
private void RefreshPing(PingReply pingReply)
{
label4.Text = (pingReply.RoundtripTime.ToString(CultureInfo.InstalledUICulture));
label5.Text = (pingReply.Status.ToString());
_avgRtt = (_avgRtt * _pingCount++ + pingReply.RoundtripTime)/_pingCount;
if (Convert.ToInt32(label4.Text) > 0 && Convert.ToInt32(label4.Text) < 100)
{
SetImage(pictureBox1, Images.Green);
}
if (Convert.ToInt32(label4.Text) > 100 && Convert.ToInt32(label4.Text) < 200)
{
SetImage(pictureBox1, Images.Yellow);
}
if (Convert.ToInt32(label4.Text) > 200 && Convert.ToInt32(label4.Text) < 1000)
{
SetImage(pictureBox1, Images.Red);
}
ToolTip tt = new ToolTip();
tt.SetToolTip(pictureBox1, "Your average network delay is " + _avgRtt + "ms");
Refresh();
}
private void SetImage(PictureBox pBox, Images images)
{
switch (images)
{
case Images.Green:
if (_greenImage == null)
{
_greenImage = new Bitmap("greenImage.png");
}
pictureBox1.Image = _greenImage;
break;
case Images.Yellow:
if (_greenImage == null)
{
_yellowImage = new Bitmap("yellowImage.png");
}
pictureBox1.Image = _yellowImage;
break;
case Images.Red:
if (_redImage == null)
{
_redImage = new Bitmap("redImage.png");
}
pictureBox1.Image = _greenImage;
break;
default:
throw new InvalidEnumArgumentException("invalid enum name");
}
}
}
internal enum Images
{
Green,
Yellow,
Red
}
}
I have a program that gets the incoming number, date and time. I want to check however if the person who is ringing me has put the phone down, how can I do this?
Below is the code which I currently have:
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.IO.Ports;
namespace CallerID
{
public partial class CallerID : Form
{
int timesTicked = 0;
Point defaultLocation = new Point();
Point newLocation = new Point();
public CallerID()
{
InitializeComponent();
port.Open();
SetModem(); // SetModem(); originally went after WatchModem();
WatchModem();
//SetModem();
telephoneTimer.Interval = 16;
telephoneTimer.Tick += new EventHandler(telephoneTimer_Tick);
defaultLocation = pictureBox1.Location;
newLocation = pictureBox1.Location;
}
void telephoneTimer_Tick(object sender, EventArgs e)
{
if (timesTicked <= 2)
newLocation.X++;
if (timesTicked >= 4)
newLocation.X--;
if (timesTicked == 6)
{
timesTicked = 0;
pictureBox1.Location = defaultLocation;
newLocation = defaultLocation;
}
pictureBox1.Location = newLocation;
timesTicked++;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
WatchModem();
}
private SerialPort port = new SerialPort("COM3");
string CallName;
string CallNumber;
string ReadData;
private void SetModem()
{
port.WriteLine("AT+VCID=1\n");
//port.WriteLine("AT+VCID=1");
port.RtsEnable = true;
}
private void WatchModem()
{
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
public delegate void SetCallerIdText();
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
ReadData = port.ReadExisting();
//Add code to split up/decode the incoming data
//if (lblCallerIDTitle.InvokeRequired)
if (ReadData.Contains("NMBR"))
{
lblData.Invoke(new SetCallerIdText(() => lblData.Text = ReadData));
}
//else
// lblCallerIDTitle.Text = ReadData;
}
private void lblData_TextChanged(object sender, EventArgs e)
{
telephoneTimer.Start();
button1.Visible = true;
}
}
}
Please ignore the Timer Code as that is just for animation.
Have you tried the PinChanged event? Normally Carrier Detect will go low when the remote end disconnects.