How to detect my application is idle in c#? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Check if an application is idle for a time period and lock it
Suppose I have a Windows product developed with C#. Now a requirement comes that if that application running and idle and when user try to interact with that application again then a login screen come. How to detect that my applications is idle when it is running? Please guide me to complete the job.

Add a timer control to your
application.
Subscribe to mouseover and keydown
events - when they fire, reset the
timer.
When the timer fires (ie mouse
hasn't moved and key's haven't been
pressed for x amount of time), lock
the screen / prompt for login.

You can use Control.LostFocus to record time when user navigated away then use Control.GotFocus to check how much time has passed to determine whether or not they need to log in.

Here go my simple solution:
Point cursorPoint;
int minutesIdle=0;
private bool isIdle(int minutes)
{
return minutesIdle >= minutes;
}
private void idleTimer_Tick(object sender, EventArgs e)
{
if (Cursor.Position != cursorPoint)
{
// The mouse moved since last check
minutesIdle = 0;
}
else
{
// Mouse still stoped
minutesIdle++;
}
// Save current position
cursorPoint = Cursor.Position;
}
You can setup a timer running on 60000 interval. By this way you will just know how many minutes the user don't move the mice. You can also call "isIdle" on the Tick event itself to check on each interval.

Capture the leave event of the Form class object to know it has lost focus.

Related

How to stop a user from clicking anywhere on the screen during session activity

I am writing an automation application where a program is opened and while that program is opened I don't want the user to be allowed to click anywhere on the screen as that will cause the automation to possibly fail at specific points.I have not been able to find anyone who has a solution to this, most of the solutions only provide answers for buttons or specific windows, but I want to disable the mouse click entirely for the user. Is there a way to do this?
Use a global mouse hook
Use a global mouse hook to monitor and optionally block mouse events.
An example implementation of global mouse/keyboard hook is MouseKeyHook nuget package and the GitHub source code globalmousekeyhook.
Blocking only user clicks
If you want to prevent the user from clicking but keep sending automation clicks, you can raise a flag to signal to the mouse down event not to block the next click.
Note: There is a small chance that in the small amount of time from when the flag was raised until the event filters the next mouse down, a user click will be captured by the hook instead of the automation click.
Blocking mouse down events example
In the following code, I give an example of using MouseKeyHook nuget package to prevent mouse clicks globally for a TimeSpan amount of time:
Required using declarations:
using System.Diagnostics;
using Gma.System.MouseKeyHook;
Code:
// Global hook
private IKeyboardMouseEvents _globalHook;
// Stopwatch to count the amount of time the global mouse down events are blocked
private Stopwatch _stopwatch = new Stopwatch();
// The amount of time to block global mouse down events
private TimeSpan _timeSpan;
// Attach global hook
private void Subscribe()
{
_globalHook = Hook.GlobalEvents();
_globalHook.MouseDownExt += GlobalHookMouseDownExt;
}
// Remove global hook
private void Unsubscribe()
{
_globalHook.MouseDownExt -= GlobalHookMouseDownExt;
_globalHook.Dispose();
}
// Global hook mouse down event
private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
{
if(_stopwatch.IsRunning)
{
if(_stopwatch.Elapsed < _timeSpan)
{
e.Handled = true;
}
else
{
_stopwatch.Stop();
}
}
}
// Block global mouse down events for timeSpan amount of time
private void BlockMouseDown(TimeSpan timeSpan)
{
_timeSpan = timeSpan;
_stopwatch.Restart();
}
Usage:
// Attach global hook
Subscribe();
...
// Block mouse down event for 10 seconds
BlockMouseDown(TimeSpan.FromSeconds(10));

How to trigger an event after a timer runs down if the user does not click a control

I'm new to stackoverflow so please forgive any protocol transgressions.
I'm trying to put together a 'times tables' practice program for my grand-daughter using c#. I'm very new to programming (just past the 'Hello World' stage). I have a 'greetings' form set up where the user (my grand-daughter, usually but not always) is asked for her name and, on pressing the Enter key, is greeted with a Textbox containing a friendly message and a request to click on the message if she'd like to 'play'. If she clicks, she is taken to a combo-box where she can choose a 'game'. I would like to attach a timer to that Textbox which shows another Textbox if she doesn't click within, say, 5 seconds. I have got as far as attaching a Timer to the form and enabling it, but cannot work out what to do next. This is the code I have so far:
private void playerOneNameTextbox_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
greetingsTextbox.Visible = true;
greetingsTextbox.Text = "Hi, " + playerOneNameTextbox.Text +
". It's good to see you. Click here if you'd like to play with us";
timer1.Enabled = true;
/*If there is no click within five seconds,
*another textbox should become visible offering another chance to click.
*/
}
private void greetingsTextbox_Click(object sender, EventArgs e)
{
youHaveClickedLabel.Visible = true;
chooseGameComboBox.Visible = true;
}
Apologies if this question is too wordy - please let me know if it is and I'll try to be more succinct next time. Many thanks.
You haven't included any details on how the timer has been set up (or what type of Timer it is, as I believe there are several).
I'm going with the assumption that you've designed the form through Visual Studio and have dragged in a Timer from the Toolbox.
This being the case, it should be a System.Windows.Forms.Timer timer object.
This type of timer has a Tick event which you will need to associate to an event handler. In VS you would do this by right-clicking on the timer1 object (located at the bottom of the design window) and selecting Properties. In the resulting properties window, click on the Events button (which looks like a lightning bolt). In here you'll have the one event "Tick".
Double-click on this and it'll automatically create the event handler stub code which you can then modify to do what you require with it.
You may wish to change the value of Interval on the timer1 object as this is the length of time (in milliseconds) which would elapse before it fires the Tick event, so in your case you'd want it to read 5000.

XNA Game does not update while "dragging" window, any event handlers?

I'm new with XNA and C#, and I've come to the point in my XNA project where I need event handlers to predict when the game loses focus so that I can sync music and visuals once it gains focus again. But I got one problem; the game does not "update" while being dragged, but I can't seem to find an suitable event listener for this. I've tried:
System.Windows.Forms.Control.FromHandle(Window.Handle).Move += new EventHandler(DeactivateGame);
This one calls "DeactivateGame" tons of times while moving the window. But even if it works, despite the fact it calls the function more than once, I can't see a event handler that calls a function when the window handle is released so that the game can resume again by calling "ActivateGame"
A sidenote (if it helps);
this.Activated += new EventHandler<EventArgs>(NotifyActivated);
this.Deactivated += new EventHandler<EventArgs>(NotifyDeactivated);
These event handlers works fine when minimizing the window or putting focus on something else than the game window, but it does not register the window being dragged. Maybe obvious for the one used to programming, but I just want to make sure I've given enough information
EDIT:
The function I want to add as the result of the event handler is a DateTime/TimeSpan that gets called when the window is out of focus or dragged. When dropped or gets focus again, this will compare the current time with the time set when the window lost focus to calculate the lost time in between.
For detecting when the XNA window is being dragged, you were on the right track using the Window.Handle with Windows Forms. You can simply listen to the ResizeBegin and ResizeEnd events to know when the user starts moving the window and when they release it.
var xnaWinForm = (System.Windows.Forms.Control.FromHandle(Window.Handle) as System.Windows.Forms.Form);
if (xnaWinForm != null)
{
xnaWinForm.ResizeBegin += new EventHandler(xnaWinForm_ResizeBegin);
xnaWinForm.ResizeEnd += new EventHandler(xnaWinForm_ResizeEnd);
}
And here's what the event handlers look like.
void xnaWinForm_ResizeBegin(object sender, EventArgs e)
{
// XNA window is starting to be moved.
}
void xnaWinForm_ResizeEnd(object sender, EventArgs e)
{
// XNA window was released and is no longer being moved.
}
Then just combine this with the other events you mentioned for determining when the window is minimized/restored/active to determine how long the window has been "inactive" for.

Click button automatically at regular intervals

I have a web application that generates enlarged images of smaller images uploaded by other team and stops if no image is left in uploaded folder.
A button needs to be clicked to start generating image and restart every time it finishes.
Can this click event be fired automatically at regular interval say at 15 minutes or better still just as the application stops.
A similar question was asked on earlier thread How to write C# Scheduler .
private void OnTimerTick()
{
if (DateTime.Now.Minutes % 15 == 0)
{
// Do something
}
}
Where should I place timer to call below code ?
protected void btnImgGenerate_click()
{
// Application code
}
Is there a way to check whether a web application in asp.net has stopped executing and then restart it automatically?
Using timer, I can schedule application to start and stop at specific time of day and keep application running throughout specified duration of day using second method.
You can add code to initialize timer from the System.Threading namespace in Global.asax file and configure it to execute some functionality with desired periodicy. But if your application crashes you'll get following issue:
Is there a way to check whether a web application in asp.net has
stopped executing and then restart it automatically ?
Using timer , I can schedule application to start and stop at specific
time of day and keep application running throughout specified duration
of day using second method .
Nope. You can't start web appliccation from itself if it stopped by some reasons and no new requests comes. So in my opinion for your purpose better suited a windows service.
A jQuery implementation for clicking a button after 15 minutes (which will cause a postback and trigger your event) is:
$(document).ready(function(){
setTimeout(function(){$('btnImgGenerate').click();},900000);
});
Have a Button click event that starts the timer-
protected void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
and in the timer Tick event, you can do something like this-
protected void timer1_Tick(object sender, EventArgs e)
{
timer1.enabled=false;
//do your coding
timer1.enabled= true;
}
So once you click the button the timer starts, does all the operations and at the end restarts automatically, after you set timer1.enabled to true.
If you are looking for automating this without the click event, you can use the javascript setInterval() Method-
See the example here-
http://www.w3schools.com/jsref/met_win_setinterval.asp

C# Slideshow only displays last image after time is up for all slides/picturebox not becoming visible

I am currently trying to create a program that will show a slideshow of pictures from an ImageList with variable show times from a ListView, which is acessed through a numericUpDown, but when I click the button to start, nothing happens, until the time of the slideshow ends, where the last slide is shown, then disappears straight away (if i leave out "pictureBox1.Visible = false" at the end, it stays).
current code:
private void buttonSlideshow_Click(object sender, EventArgs e)
{
pictureBox1.Visible = true;
for (int s = 0; s < listView1.Items.Count; s++)
{
listView1.Items[s].Selected = true;
pictureBox1.Image = imageList1.Images[s];
DateTime later = DateTime.Now.AddMilliseconds((double)numericUpDown1);
while (DateTime.Now < later)
{
}
}
pictureBox1.Visible = false;
}
I have tried many versions of this (including using timers and switching code around) have no idea what is going wrong
numericUpDown1 is the duration of the slide, have been using integers for testing, still doesn't work
Doing this:
while (DateTime.Now < later)
Is blocking your UI thread. It can't redraw the screen while you are keeping it busy spinning it's wheels. Use a timer with a call back instead.
You'll need to rework your code slightly. Rather than use a for loop, define a variable for your current slide, initialize it to zero in your click handler, make your picture box visible, load the first picture and then start your timer.
In your timer handler, you'll increment the current index, check it against the length of you list of slides and, if you still have slides to display, load the next one and then start the timer again (or you can use a timer that fires repeatedly, although you might want to be careful that it doesn't fire again before you're done handling that last one). If there are no more slides left, just do you clean up and make your picture box invisible again.
One final note, be careful with which thread the timer is going to fire on. In win forms you can use System.Windows.Forms.Timer which fires on the UI thread and you won't have any problems. In WPF you can use DispatcherTimer which also fires on the UI thread. Other timers generally run in their own thread and you'll have to handle pushing anything that's supposed to update the UI back to the UI thread.

Categories