I read time from php with C#. I have to show MessageBox before Logoff windows when the time is equal. But when I run program it show same MessageBox 2 time. I want to show MessageBox 1 time only before Logoff. I set Interval is 30,000. How to do it? This is my code
private void timer1_Tick(object sender, EventArgs e)
{
bool showingBox = false;
timer1.Start();
WebClient client = new WebClient();
Stream stream = client.OpenRead("http://172.22.22.20/time.php");
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
//textBox1.Text = content;
if (showingBox) return;
showingBox = true;
try
{
if (content == "08:00")
{
MessageBox.Show(new Form() { TopMost = true }, "11111"); // This will show 2 Message Box when time = 08.00
}
}
finally
{
showingBox = false;
}
if (content == "08:05")
{
ExitWindowsEx(4, 0);
}
timer1.Enabled = false;
}
}
}
I don't know if i understand your question right, but could it be that you start the timer twice ?
As far as i can see you do start the timer again in your timer_tick method
private void timer1_Tick(object sender, EventArgs e)
{
bool showingBox = false;
timer1.Start(); // <-- second time startet.
Why you using timer1.Start(); in timer1_Tick Event?
I remove timer1.Start() but it also show twice messagebox . I change the code like this flag = true; have to run before show message box . Now it work!!.
if (content == "10:09")
{
if (!flag)
{
flag = true;
MessageBox.Show(new Form() { TopMost = true }, "11111" +flag);
}
}
Related
I would like to check updates from txt file on web server. and send a messagebox when there is version mismatch, I'm using this code and it works but I want it only to connect the server every 10 minutes and check the text file.
is there any option to do that?
maybe using another way to create this loop?
I also would like to send the messagebox only once
bool hasDisplayed = false;
private string UpdateCheckServer()
{
WebClient client = new WebClient();
Stream stream = client.OpenRead("http://localhost/update/update_version.txt");
StreamReader reader = new StreamReader(stream);
string serverversion = reader.ReadToEnd();
return serverversion;
}
private string UpdateCheckClient()
{
string ClientVersion = System.IO.File.ReadAllText("update_version.txt");
return ClientVersion;
}
private void UpdateCheckTimer()
{
while (!hasDisplayed)
{
if (starter.Enabled == true && UpdateCheckServer() == UpdateCheckClient())
{
//Nothing here
}
if (starter.Enabled == true && UpdateCheckServer() != UpdateCheckClient())
{
MessageBox.Show("not updated");
hasDisplayed = true;
}
}
An implementation based on timer can look like this:
private bool _equalVersion = true;
private System.Timers.Timer _timer = new System.Timers.Timer(1000 * 60 * 10); //millisecond * seconds * minutes
private void StartUpdateCheckTimer()
{
_timer.Elapsed += UpdateCheck;
_timer.Start();
}
private void UpdateCheck(object sender, ElapsedEventArgs e)
{
_timer.Stop();
_equalVersion = (UpdateCheckServer() == UpdateCheckClient());
if (!_equalVersion)
{
MessageBox.Show("not updated");
}
else
{
_timer.Start();
}
}
in this way you get a timer:
triggered each 10 minutes,
performing the check
notifying the version change (and stopping) or proceeding with the subsequent iterations
then you can add some more logic like for example reset of the check, more proper notification action (separating your check routine from the GUI part) and many more.
Another approach (as pointed out by #imsmn) can be to make your implementation System.Threading.Sleep based, but I'd suggest the first option based on timer.
After several tries and learning I managed to do that.
private string UpdateCheckServer()
{
WebClient client = new WebClient();
Stream stream = client.OpenRead("http://localhost/update/update_version.txt");
StreamReader reader = new StreamReader(stream);
string serverversion = reader.ReadToEnd();
return serverversion;
}
private string UpdateCheckClient()
{
string ClientVersion = System.IO.File.ReadAllText("update_version.txt");
return ClientVersion;
}
private void UpdateCheckTimer()
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
void timer_Tick(object sender, EventArgs e)
{
//Call method
if (starter.Enabled == true && UpdateCheckServer() != UpdateCheckClient())
{
t.Stop();
MessageBox.Show("not updated");
}
}
}
I have a button on my program that checks a port. but if I put a port that is closed and I click to test it, if it is open I immediately get the green button. If it is not open instead the program is "freezed" for about ten seconds and then it gives me the red button. The problem is that if by mistake I click on the button while the program is in this phase of "freeze", then when it ends, restarts from the beginning and re-freezes, probably because it still felt the button click for the second time. how can I prevent this from happening?
button_click
private void bt_check_port_Click(object sender, EventArgs e)
{
bt_check_port.BackColor = SystemColors.Control;
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect(tb_ip_test.Text, Int32.Parse(tb_port_test.Text));
bt_check_port.BackColor = Color.Green;
}
catch (Exception)
{
bt_check_port.BackColor = Color.Red;
}
}
First you should go async, so you don't block the gui for long running tasks.
Then bypass the code while its executing, so it's not executed in parallel.
Also you should visibly inform the user that the button is currently not working(e.g. disable the button or display a wait indicator).
something like this:
private bool isWorking = false;
private async void bt_check_port_Click(object sender, EventArgs e)
{
if (!isWorking)
{
isWorking = true;
try
{
bt_check_port.Enabled = false;
bt_check_port.BackColor = SystemColors.Control;
string ip = tb_ip_test.Text;
string port = tb_port_test.Text;
bool portAwailable = await Task.Run<bool>(() =>
{
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect(ip, Int32.Parse(port));
return true;
}
catch (Exception)
{
return false;
}
});
bt_check_port.BackColor = portAwailable ? Color.Green : Color.Red;
}
finally
{
isWorking = false;
bt_check_port.Enabled = true;
}
}
}
I have made an windows form, with an initializing (form) which later redirects to the main form. The problem is it takes about three seconds to load, which make the user interface look really bad. The buttons are white, until they load, then they show the text and the colors. Is there any way to pre-load the form, but hide it, until the initializing (form) is finished?
For those who ask why it takes so long, I have a web browser which imports local HTML and it has InvokeText and addBase, addMaths and other items
This is the load script, how it loads the web browser
private async void TextEdit_Load(object sender, EventArgs e)
{
WebClient wc = new WebClient();
wc.Proxy = null;
try
{
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
string friendlyName = AppDomain.CurrentDomain.FriendlyName;
bool flag2 = registryKey.GetValue(friendlyName) == null;
if (flag2)
{
registryKey.SetValue(friendlyName, 11001, RegistryValueKind.DWord);
}
registryKey = null;
friendlyName = null;
}
catch (Exception)
{
}
webBrowser1.Url = new Uri(string.Format("file:///{0}/Files/TextEditor/Editor.html", Directory.GetCurrentDirectory()));
The next bit is the functionality of the web browser
await Task.Delay(500);
webBrowser1.Document.InvokeScript("SetTheme", new string[]
{
"Dark"
});
addBase();
addMath();
addGlobalNS();
addGlobalV();
addGlobalF();
webBrowser1.Document.InvokeScript("SetText", new object[]
{
""
});
}
I guess it is the problem with the webBrowser (text editor) because when I delete it, it no longer takes 3 seconds loading time.
For those who say use This.Hide(); and This.Show();, it does not work, because the web browser won't load at all.
if the main issue is that it takes about three seconds to load, then consider Threading on your form's Load event (provided you placed all pre-requisite loading there). This way you can initially disable controls prior to the form being displayed and enable controls once the entire process is finished. See below example:
private void Form1_Load(object sender, EventArgs e)
{
#region Disable controls here
textbox1.Enabled = false;
button1.Enabled = false;
combobox1.Enabled = false;
#endregion
Task.Factory.StartNew(() => {
try
{
// Do Long running processing of form prerequisites here.
...
// Enable controls here once processing is sucessful and complete.
Invoke((Action) (() => {
textbox1.Enabled = true;
button1.Enabled = true;
combobox1.Enabled = true;
}));
}
catch(Exception e)
{
Invoke((Action) (() => {
MessageBox.Show(e.Message);
}));
}
});
}
I have an application where user can click on a Scan button to scan the image to preview in the application. When user clicks, usually a "Preparing to scan" message will be shown and goes away when the scan is 100% complete.
The scan works fine. The problem if I stress test it by pressing the scan button many times while it's doing it's work, the application completely hangs and the message just stays there and I had to restart my whole application.
The code: It's just a small section
private void ScanStripButton_Click(object sender, EventArgs e)
{
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
}
Any idea on how to prevent this issue?
Appreciate the help
EDIT:
public void StartTwainScan()
{
Boolean EnableUI = false;
Boolean ADF = false;
Boolean EnableDuplex = false;
if (Properties.Settings.Default.TwainShow.Equals("1"))
{
EnableUI = true;
}
if (Properties.Settings.Default.ScanType.Equals("2"))
{
ADF = true;
}
if (Properties.Settings.Default.DuplexEnable.Equals("1"))
{
EnableDuplex = true;
}
var rs = new ResolutionSettings
{
Dpi = GetResolution(),
ColourSetting = GetColorType()
};
var pg = new PageSettings()
{
Size = GetPageSize()
};
var settings = new ScanSettings
{
UseDocumentFeeder = ADF,
ShowTwainUI = EnableUI,
ShowProgressIndicatorUI = true,
UseDuplex = EnableDuplex,
Resolution = rs,
Page = pg
};
try
{
TwainHandler.StartScanning(settings);
}
catch (TwainException ex)
{
MessageBox.Show(ex.Message);
//Enabled = true;
//BringToFront();
}
}
This isn't going to be the correct answer, but you haven't shown enough code to give you the right code. It should point you in the right direction.
private void ScanStripButton_Click(object sender, EventArgs e)
{
ScanStripButton.Enabled = false;
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
ScanStripButton.Enabled = true;
}
Basically you disable the button when the scan starts and enable it when it finishes.
private async void ScanStripButton_Click(object sender, EventArgs e)
{
await Task.Run(() =>
{
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
});
}
or
private bool clicked = false;
private void ScanStripButton_Click(object sender, EventArgs e)
{
try
{
if(clicked)
return;
clicked = true;
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
}
finally
{
clicked = false;
}
}
I am making an audio recorded using NAudio in C# and i need to remove the stop button used and simply stop the recording on its own after some time delay.
The code for the record event is
private void cmbRecord_Click(object sender, EventArgs e)
{
outputFilename = "file address";
waveInStream = new WaveIn(44100,2);
writer = new WaveFileWriter(outputFilename, waveInStream.WaveFormat);
waveInStream.DataAvailable += new EventHandler<WaveInEventArgs>(waveInStream_DataAvailable);
waveInStream.StartRecording();
// Just controling the objects on the screen.
cmbRecord.Enabled = false;
cmbStop.Enabled = true;
}
void waveInStream_DataAvailable(object sender, WaveInEventArgs e)
{
writer.WriteData(e.Buffer, 0, e.BytesRecorded);
int secondsRecorded = (int)(writer.Length / writer.WaveFormat.AverageBytesPerSecond);
}
The stop button is given as
private void cmbStop_Click(object sender, EventArgs e)
{
waveInStream.StopRecording();
waveInStream.Dispose();
waveInStream = null;
writer.Close();
writer = null;
cmbRecord.Enabled = true;
cmbStop.Enabled = false;
}
I need to stop the recording automatically inside the cmbRecord_Click event.
Thanks in advance.
use a Timer, set the Interval and copy the code in cmbStop_Click event over to timer's OnTick event. Enable the timer in the mbRecord_Click event and & remember to disable the timer in cmbStop_Click event
Edit:
Create a new timer and set its value
//put this line in your form class level
System.Windows.Forms.Timer mytimer=new System.Windows.Forms.Timer(); //create a new Timer
//put these two into your form constructor just after InitializeComponent();
mytimer.Interval=1000; //set the interval to 1 second.
mytimer.Tick += new EventHandler(mytimer_Tick);
Enable the timer in the mbRecord_Click event
private void cmbRecord_Click(object sender, EventArgs e)
{
outputFilename = "file address";
waveInStream = new WaveIn(44100,2);
writer = new WaveFileWriter(outputFilename, waveInStream.WaveFormat);
waveInStream.DataAvailable += new EventHandler<WaveInEventArgs>(waveInStream_DataAvailable);
waveInStream.StartRecording();
// Just controling the objects on the screen.
cmbRecord.Enabled = false;
cmbStop.Enabled = true;
//Enable the timer to fire
mytimer.Enabled = true;
}
Stop recording after 1 second..
void mytimer_Tick(object sender, EventArgs e)
{
waveInStream.StopRecording();
waveInStream.Dispose();
waveInStream = null;
writer.Close();
writer = null;
cmbRecord.Enabled = true;
cmbStop.Enabled = false;
//disable the timer here so it won't fire again...
mytimer.Enabled = false;
}
One thing you may want to bear in mind - there will be a DataAvailable callback after the call to StopRecording (or during, depending on the callback model used), so you might want to delay closing the WaveFileWriter until you have written everything.
Have a look at the VoiceRecorder sample project which uses NAudio and stops recording after 60 seconds. I explain in this article how recording is automatically stopped.
long maxFileLength = this.recordingFormat.AverageBytesPerSecond * 60;
int toWrite = (int)Math.Min(maxFileLength - writer.Length, bytesRecorded);
if (toWrite > 0)
writer.WriteData(buffer, 0, bytesRecorded);
else
Stop();