Making an Alarm Clock with multiple alarm times - c#

I am trying to make a programmable alarm clock. It should output a melody (.wav) at different moments of time. I used a usercontrol to make a digital clock. I have a timer for showing a progressbar to every second and a button that starts the process. I know exactly the times I want so I don't need any other button. I made some functions where I complete the times I need.
public void suna3()
{
userControl11.Ora = 01;
userControl11.Min = 37;
userControl11.Sec = 50;
}
and on the button click I called them. But when I start the program it is taking only the last time I made (the last function). How can I make it take all the functions?
private void button3_Click(object sender, EventArgs e)
{
userControl11.Activ = true;
suna1();
userControl11.Activ = true;
suna2();
}

I think the problem is that you are using the same timer for three different events, changing the settings of it three times. This results in only the final settings being used - the older settings are not remembered - they are overwritten.
The solution is to create a new timer for each event, each timer having its own separate settings.

You need a usercontrol for each alarm time, or change your user control so that it takes in an array of times to trigger the alarm at.
For multiple usercontrol instances, your code could look something like this:
public void suna1()
{
userControl11.Ora = 02;
userControl11.Min = 27;
userControl11.Sec = 20;
}
//...
public void suna3()
{
userControl13.Ora = 01;
userControl13.Min = 37;
userControl13.Sec = 50;
}
The alternative is to change your usercontrol so that it accepts a list of times, or has an AddAlarm() method. Something like this:
public void suna1()
{
userControl11.Alarms.Add(new Alarm() { Ora = 02, Min = 27, Sec = 20 };
//or "userControl1.AddAlarm(2, 27, 20);" if you go the method route
}
//...
public void suna3()
{
userControl11.Alarms.Add(new Alarm() { Ora = 01, Min = 37, Sec = 50 };
}

Related

Unity Toggle Button Delay

I'm trying to make it so my toggle = !toggle doesn't just repeat OVER and OVER when you press it once because it kind of toggles on and off over and over if you hold it it just keeps toggling like 30 times a second and I want it to have a delay here is the gist of my code
private class AirJump_Patch
{
private static void Postfix (Locomotion.Player __instance)
{
List<InputDevice> list = new List<InputDevice>();
InputDevices.GetDevicesWithCharacteristics(InputDeviceCharacteristics.HeldInHand |
InputDeviceCharacteristics.Controller | InputDeviceCharacteristics.Right, list);
list[0].TryGetFeatureValue(CommonUsages.secondaryButton, out
Plugin.AirJump_Patch.secondaryButton);
if (Plugin.AirJump_Patch.secondaryButton)
{
Plugin.AirJump_Patch.jumpToggled = !Plugin.AirJump_Patch.jumpToggled;
}
if (!Plugin.AirJump_Patch.jumpToggled)
{
//DO CODE
}
ECT ECT.
I tried adding delay using StartCoroutine, doesn't work
I tried adding delay using simple C# wait things, doesn't work
This is in a private static void. I cannot change that. Is there a reasonably easy way to make the toggle not repeat 30 times a second with a 0.5 second delay or so?
Maybe you could use a simple timer field like
private float lastToggle;
and then
if(Time.time > lastToggle + 0.5f)
{
lastToggle = Time.time;
Plugin.AirJump_Patch.jumpToggled = !Plugin.AirJump_Patch.jumpToggled;
}
Alternatively you could actually handle it really only once e.g. like
private bool alreadyToggled;
if(Plugin.AirJump_Patch.secondaryButton)
{
if(!alreadyToggled)
{
Plugin.AirJump_Patch.jumpToggled = !Plugin.AirJump_Patch.jumpToggled;
alreadyToggled = true;
}
}
else
{
alreadyToggled = false;
}
now it is really only handled once per button press.

c# coding a timed operation within a for loop

I am writing a piece of code that takes a user through a guided script. The user will have a few seconds to answer before the answer will be displayed.
So far, my code looks like this:
GuidedExercise3 exercise3 = new GuidedExercise3();
string AntonioAnswer = string.Empty; // expected answer
int upperBound = exercise3.Script.Count - 1; // zero-based counting
for(int i = 0; i < upperBound; i += 2)
{
labelInstructions.Text = exercise3.Script[i].TextToSpeak;
AntonioAnswer = exercise3.Script[i+1].TextToSpeak; // answer
SetTimer(AntonioAnswer, txtAntonio); // set timer sending in the answer and the TextBox object.
sysTimer.Start();
}
The odd lines of a List contain the question and the even lines contain the expected answer. My question is how do I display the question for X seconds and then get the user's answer in this WinForms app and then display the answer when the timer elapses, keeping the user from going to the next step of the script but allowing them to answer the question (which is in a Textbox).
I examined this StackOverflow question, but it doesn't match: Implementing a loop using a timer in C#
Here's how I would handle something like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
MoveNextQuestion();
timerAnswer.Interval = 5000;
timerAnswer.Start();
}
private string[] _questionsAndAnswers = new[]
{
"What colour is the sky?",
"Blue",
"What do chickens lay?",
"Eggs",
};
private int _currentIndex = -2;
private void timerAnswer_Tick(object sender, EventArgs e)
{
MoveNextQuestion();
}
private void buttonAnswer_Click(object sender, EventArgs e)
{
MoveNextQuestion();
}
private void MoveNextQuestion()
{
_currentIndex += 2;
if (_currentIndex < _questionsAndAnswers.Length)
{
labelQuestion.Text = _questionsAndAnswers[_currentIndex];
}
else
{
timerAnswer.Stop();
}
}
}
I was able to get this working fairly easily with a BackgroundWorker object. See the following article at MSDN for the exact coding. BackgroundWorker Class. In particular they have two examples in the documentation and the first example is sufficient. The BackgroundWorker class is allowing my UI to continue to accept user input while waiting on a timed answer. It displays the correct answer on the RunWorkerComplete event. So the BackgroundWorker's RunAsync gets called in my for loop.
I've run into the additional issue of the BackgroundWorker not returning control to my loop. I'm looking into that problem separately.

How to check if an incident happened during a time frame in C#?

I am developing software that adds if a button is clicked 5 times, a variable is incremented by '1'
IF A then B++
everything is good, but now I want the system to reset its counter if that 5 times did not happen within 10 seconds. I.e the speed of clicking matters.
If I click too slow, the increment should not happen even though I clicked 5 times as it exceeds that 10 secs period.
Any suggestion?
This could be done much nicer but it should work:
DateTime time = new DateTime();//time of first click
int counter = 0;
void button_click(object sender, EventArgs e)
{
if(counter == 0)
{time = DateTime.Now}
else if(counter == 5)
{
if( DateTime.Now.Subtract(time).Duration().Seconds <= 10)
{/*Do some cool stuff*/}
else
{counter = -1;}
}
counter++;
}
I'd do something like this:
const int ClicksRequired = 5;
readonly TimeSpan ClickTimeSpan = new TimeSpan(0, 0, 10);
Queue<DateTime> _clicks = new Queue<DateTime>();
private void clickTarget_MouseUp(object sender, MouseEventArgs e)
{
var currentTime = DateTime.Now;
_clicks.Enqueue(currentTime);
if (_clicks.Count == ClicksRequired)
{
var firstTime = _clicks.Dequeue();
if (currentTime - firstTime <= ClickTimeSpan)
{
MessageBox.Show("Hello World!");
_clicks.Clear();
}
}
}
I use Queue to keep track of clicks because you don't know which mouse click will actually be the first click until you have five clicks in the time window. You need to know the time of the fifth click back in time and that click changes with each subsequent click.
I use MouseUp instead of Click because Click might not fire the correct number of times if clicks occur within the system double-click interval (because those get routed to DoubleClick).

How to using Timer in c# to hovering button?

I want to make hovering button in my game. Because when my cursor touch the button it will go to another screen immediately. I don't like this so much. I use xna 4.0 with visual studio 2010 to make this project. (use kinect without wpf)
How to use timer in this case ? Please help me
if (Hand.contian(Button) && holdtime == targetHoldtime)
{
}
You have to manage time by yourself based in elapsed time per frame:
ft = GameTime.Elapsed.TotalSeconds; // Xna
ft= 1/30f; // 30fps
And can be done in similar way to this:
class Button {
public float Duration = 1; // One second
public Rectangle Bounds; // Button boundaries
public float Progress { get{ return Elapsed/Duration; } }
float Elapsed = 0;
public void Update(float ft) {
if (Bounds.Contains( HandPosition ))
{
if (Elapsed<Duration) {
Elapsed += ft;
if (Elapsed>Duration) {
Elapsed = Duration;
OnClick();
}
}
} else {
Elapsed = 0;
}
}
}
I would first suggest that you look through the SDK documentation and the built in KinectInteraction controls. They may provide you with what you are looking for. Most notably SDK 1.7 removed that "HoverDwell" button in favor of a "press" action, which is a more natural interaction in a gesture system. You may want to look at using that motion instead.
If you truly desire a "click on hover" type action, you can look at the code in SDK 1.6 for an example. Several examples are available online at the Kinect for Windows CodePlex repository. The specific control example you are looking for is in the "BasicInteraction-WPF" project, and is called HoverDwellButton.
The "button" is actually a ContentControl which means you can place any content in there to make it a button. It can be a simple image, or a complex Grid. It has all the hooks to fire events when the timer on your hover goes off.
There is a decent amount of complexity in this control, which is what makes it work for a wide range of applications. At the core of the interaction is a simple DispatcherTimer.
private void OnPreviewHandEnter(object sender, HandInputEventArgs args)
{
if (this.trackedHandHovers.FirstOrDefault(t => t.Hand.Equals(args.Hand)) == null)
{
// additional logic removed for answer sanity
var timer = new HandHoverTimer(DispatcherPriority.Normal, this.Dispatcher);
timer.Hand = args.Hand;
timer.Interval = TimeSpan.FromMilliseconds(Settings.Default.SelectionTime);
timer.Tick += (o, s) => { this.InvokeHoverClick(args.Hand); };
this.trackedHandHovers.Add(timer);
timer.Start();
}
args.Handled = true;
}
Notice that the Tick event is calling InvokeHoverClick, which (in part) reads as follows:
public void InvokeHoverClick(HandPosition hand)
{
// additional logic removed for answer sanity
var t = new DispatcherTimer();
t.Interval = TimeSpan.FromSeconds(0.6);
t.Tick += (o, s) =>
{
t.Stop();
var clickArgs = new HandInputEventArgs(HoverClickEvent, this, hand);
this.RaiseEvent(clickArgs);
this.IsSelected = false;
};
t.Start();
}
This now fires an event after a set amount of time. This event can be capture and acted upon to your liking.
Again, I first recommend looking at the newer interactions in SDK 1.7. If you still want a timed hover click action, check out the links above. I used the HoverDwellButton to great effect in several different areas.

Simple button animations

I am trying to learn .NET programming. As a part of my learning, I tried to make some effects on buttons. It is working... but not as smooth as I imagined! Is there any better way to do this? Thank you in advance!
My need:
There are 3 buttons.
When you hover the mouse over one of them, it expands and when you mouse out from that button, it returns to its initial size.
private void button1_MouseHover(object sender, EventArgs e)
{
button1.BackColor = Color.White;
button1.Width = 130;
button1.BringToFront();
}
private void button1_MouseLeave(object sender, EventArgs e)
{
button1.BackColor = Color.Red;
button1.Width = 75;
}
private void button2_MouseHover(object sender, EventArgs e)
{
button2.BackColor = Color.Gray;
button2.Width = 130;
button2.BringToFront();
}
private void Form1_MouseLeave(object sender, EventArgs e)
{
button2.BackColor = Color.Red;
button2.Width = 75;
}
private void button3_MouseHover(object sender, EventArgs e)
{
button3.BackColor = Color.DimGray;
button3.Width = 130;
button3.BringToFront();
}
private void button3_MouseLeave(object sender, EventArgs e)
{
button3.BackColor = Color.Red;
button3.Width = 75;
}
So first off, you don't want to do the exact same thing 3 times. Create a single method to add the appropriate handlers for a button, and then just write the code once to handle any given button.
Note that you can go into the expand/contract tick handlers and use the percentComplete value to set the height as well, to move the color along a spectrum (this would involve some mathematics of colors to do though) or to alter any other aspect of the button. If you're really motivated to generalize it you could add a parameter to the method of Action<double> that does something to the object based on the given percent progress.
public void AddAnimation(Button button)
{
var expandTimer = new System.Windows.Forms.Timer();
var contractTimer = new System.Windows.Forms.Timer();
expandTimer.Interval = 10;//can adjust to determine the refresh rate
contractTimer.Interval = 10;
DateTime animationStarted = DateTime.Now;
//TODO update as appropriate or make it a parameter
TimeSpan animationDuration = TimeSpan.FromMilliseconds(250);
int initialWidth = 75;
int endWidth = 130;
button.MouseHover += (_, args) =>
{
contractTimer.Stop();
expandTimer.Start();
animationStarted = DateTime.Now;
button.BackColor = Color.DimGray;
};
button.MouseLeave += (_, args) =>
{
expandTimer.Stop();
contractTimer.Start();
animationStarted = DateTime.Now;
button.BackColor = Color.Red;
};
expandTimer.Tick += (_, args) =>
{
double percentComplete = (DateTime.Now - animationStarted).Ticks
/ (double)animationDuration.Ticks;
if (percentComplete >= 1)
{
expandTimer.Stop();
}
else
{
button.Width = (int)(initialWidth +
(endWidth - initialWidth) * percentComplete);
}
};
contractTimer.Tick += (_, args) =>
{
double percentComplete = (DateTime.Now - animationStarted).Ticks
/ (double)animationDuration.Ticks;
if (percentComplete >= 1)
{
contractTimer.Stop();
}
else
{
button.Width = (int)(endWidth -
(endWidth - initialWidth) * percentComplete);
}
};
}
If you are using WinForms, animations are going to be rather painful and you will have to handle them yourself via Timer objects.
If you are getting into .NET and want to make cool-looking applications with animatons and styling, I highly recommend you look at WPF instead. It can do animations very easily though C# or XAML.
While it is still possible in WinForms, it will take far more development time where as those features are built into WPF already (and optimized).
When you modify a controls properties, it takes effect instantaneously. What you desire is something that is usually known as some type of fade or tweening. There might be libraries out there to do this, but if you wanted to write this yourself for fun, you can use a Timer object, and on each tick update the color.
What you would do is set a color as the TargetColor somewhere(this is a variable or property you make up), and then start a timer that ticks maybe every 10 milliseconds. In each tick, you look at the start time, and how long has passed since then. If you want the animation to take place of a full second, then that is 1000 milliseconds. So during each tick, you look at the amount of time that has passed, maybe 200 milliseconds, then divide 200/1000 to get the fraction of time that you have gone into the animation. Then you look at a difference between the Start and Target Color, multiply that difference by the fraction, and add the result to the start color. In other words, 200 milliseconds into an animation that last 1000 milliseconds, means you are 20% into the animation. Thus you want to set the color to be whatever color is 20% from the start color towards the end color.
There's alot you could do to refine this. Perhaps having a subclass Button control that encapsulates the timer and exposes functions/properties to track start/end color, animation transition time, etc. Most animated UI features like this let you specify how long the animation should last, and then it interpolates the inbetween states as it transitions. This is the origin of the term tweening, as it comes from transitioning from one state to another by inbetweening

Categories

Resources