How to get windows unlock event in c# windows application? - c#

I want to track the windows unlock event in a windows application. How is it done? What is the event used for that? Does I need to import any namespace for that?
While a user unlocks the windows, the application needs to do some tasks.

As posted in this StackOverflow answer: https://stackoverflow.com/a/604042/700926 you should take a look at the SystemEvents.SessionSwitch Event.
Sample code can be found in the referred answer as well.
I just took the code shown in the referred StackOverflow answer for a spin and it seems to work on Windows 8 RTM with .NET framework 4.5.
For your reference, I have included the complete sample code of the console application I just assembled.
using System;
using Microsoft.Win32;
// Based on: https://stackoverflow.com/a/604042/700926
namespace WinLockMonitor
{
class Program
{
static void Main(string[] args)
{
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
Console.ReadLine();
}
static void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
//I left my desk
Console.WriteLine("I left my desk");
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
//I returned to my desk
Console.WriteLine("I returned to my desk");
}
}
}
}

Related

Raise a .NET "OK" Event in C#?

In the documentation of the Siemens TIA-Portal Openness API you can read the following:
There is an event, when a confirmation box opens, and an event when the confirmation is given by the user.
//Register event handler for Notification-Event
....
tiaPortal.Notification += TiaPortal_Notification;
....
private static void TiaPortal_Notification(object sender, NotificationEventArgs e)
{
....
}
//Register event handler for Confirmation-Event
....
tiaPortal.Confirmation += TiaPortal_Confirmation;
....
private static void TiaPortal_Confirmation(object sender, ConfirmationEventArgs e)
{
....
}
The documentation gives this much information on reacting to the events
I want to react on the notification event. But the NotificationEventArgs Class does not contain an result attribute which i can write on, and does not contain any method of some kind to send a confirmation. There is only one writeable attribute, called IsHandled. But nothing happens if i write to that, so i suggest this is only an internal confirmation
My understanding of the api documentation ist, that it is something native of c#/.net? maybe a function of some kind, to raise reactions on events?
This answer is valid for TIA 16 with Openness API V16.
Confirmations: If a prompt is triggered in TIA Portal that requires a user decision (i.e. has more than one button), ConfirmationEvent is raised, and it definitely happens prior to any decision being made by the user.
Set IsHandled, then set the Result value. That's all you need to do.
private static void Tiap_Confirmation(object sender, ConfirmationEventArgs e)
{
//signal to TIA Portal that the event is handled
e.IsHandled = true;
//handle the various events
if (CONDITIONS_FOR_CHOOSING_YES)
e.Result = ConfirmationResult.Yes;
if (CONDITIONS_FOR_CHOOSING_CANCEL)
e.Result = ConfirmationResult.Cancel;
...
}
Notifications: NotificationEvent is only raised for prompts that have one button. The example below is for a .NET Framework console application.
using Siemens.Engineering;
using System;
using System.Linq;
using System.Threading;
namespace OpennessConsoleTests
{
class Program
{
static void Main(string[] args)
{
//attach to the first tia portal process found
TiaPortal tiap = TiaPortal.GetProcesses().First().Attach();
//subscribe to confirmation event
tiap.Notification += Tiap_Notification;
//pause
Console.WriteLine("Waiting for events. Press Ctrl+C to quit");
//sleep indefinitely. User must ctrl+C out of this
Thread.Sleep(Timeout.Infinite);
}
private static void Tiap_Notification(object sender, NotificationEventArgs e)
{
e.IsHandled = true;
Console.WriteLine("*****Notification*****");
Console.WriteLine("Caption: " + e.Caption);
Console.WriteLine("Text: " + e.Text);
Console.WriteLine("DetailText: " + e.DetailText);
}
}
}
An important note: According to my testing, some prompts do not raise an event even if subscribed, for example "Subfolder already exists" when extracting an archive. This puts TIA Portal into a locked state until you stop your application.
I think it's just a (not optimal) translation into German. What they mean is you need to set a field in the event args you got. This is a normal pattern in .NET.
Something like this (don't have the library for syntax check but you should get what I mean):
private static void TiaPortal_Confirmation(object sender, ConfirmationEventArgs e)
{
// do your thing, open a confirmation dialog or something, then:
e.Result = Choices.OK;
}

C# - getting information about Windows user local session [duplicate]

I want to track the windows unlock event in a windows application. How is it done? What is the event used for that? Does I need to import any namespace for that?
While a user unlocks the windows, the application needs to do some tasks.
As posted in this StackOverflow answer: https://stackoverflow.com/a/604042/700926 you should take a look at the SystemEvents.SessionSwitch Event.
Sample code can be found in the referred answer as well.
I just took the code shown in the referred StackOverflow answer for a spin and it seems to work on Windows 8 RTM with .NET framework 4.5.
For your reference, I have included the complete sample code of the console application I just assembled.
using System;
using Microsoft.Win32;
// Based on: https://stackoverflow.com/a/604042/700926
namespace WinLockMonitor
{
class Program
{
static void Main(string[] args)
{
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
Console.ReadLine();
}
static void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
//I left my desk
Console.WriteLine("I left my desk");
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
//I returned to my desk
Console.WriteLine("I returned to my desk");
}
}
}
}

OpenTK.Core | Does not detect my keypresses

I am following this tutorial to learn how to use OpenGL in C#. Everything ran fine until this part: OpenGL 4 with OpenTK in C# Part 10: Asteroid Invaders. I am not using the exact same OpenTK as the one used in the tutorial. I am using this version that is compatible with .NET Core here: https://www.nuget.org/packages/OpenTK.NETCore/
Issue
Seems that OpenTK does not detect my keyboard. I have a simple update loop that handles keyboard input like this:
OnUpdateFrame
protected override void OnUpdateFrame(FrameEventArgs e)
{
base.OnUpdateFrame(e);
this.HandleKeyboard(e.Time);
// {...} Update Logic
}
HandleKeyboard
protected void HandleKeyboard(double delta)
{
Console.WriteLine("Handling keyboard");
var keyState = this.Keyboard.GetState();
if (keyState.IsKeyDown(Key.Escape))
{
this.Exit();
}
if (keyState.IsKeyDown(Key.A))
{
Console.WriteLine("Moving left");
this.player.MoveLeft();
}
if (keyState.IsKeyDown(Key.D) {
Console.WriteLine("Moving right");
this.player.MoveRight();
}
if (!this.gameOver && keyState.IsKeyDown(Key.Space) && this.lastKeyboardState.IsKeyUp(Key.Space))
{
this.gameObjects.Add(this.gameObjectFactory.CreateBullet(this.player.Position));
}
this.lastKeyboardState = keyState;
}
The console shows Handling keyboard many times, when I press A or D it doesn't write Moving left or Moving right. When I debug, and hover over keystate there is a property IsConnected = false. Maybe OpenTK is not recognizing my keyboard?
I am using the laptop keyboard so nothing fancy.
According to the documentation on Keyboard.GetState() it says Gets the primary Keyboard device, or null if no keyboard exists. But it doesn't return null?
How can I solve this? Thanks
Minimal example
I tried this on a separate solution:
using System;
using OpenTK;
using OpenTK.Input;
namespace OpenTKTest
{
class Program
{
[STAThread]
static void Main(string[] args)
{
using (var window = new GameWindow())
{
window.UpdateFrame += (sender, eventArgs) =>
{
var state = window.Keyboard.GetState();
if (state.IsKeyDown(Key.A))
{
Console.WriteLine("KEYSTATE");
}
};
window.KeyDown += (sender, eventArgs) =>
{
if (eventArgs.Key == Key.A)
{
Console.WriteLine("KEYDOWN EVENT");
}
};
window.Run(60);
}
}
}
}
And effectively, when I press the A key, KEYDOWN EVENT gets written but not KEYSTATE. So definitely a bug.
From what I gather (having experienced similar results), OpenTK.Input.Keyboard API is not yet implemented.

XNA and Windows Forms

I am trying to make a main menu in Windows Forms. When you click a label in the form, the XNA game should start playing.
But it didn't work.
my code in the program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace _2DSpaceShooter
{
if WINDOWS || XBOX
static class Program
{
static void Main(string[] args)
{
Application.Run(new MainMenu());
}
}
endif
}
My code in the label click event
private void label1_Click(object sender, EventArgs e)
{
using (Game1 game = new Game1())
{
game.Run();
}
}
Please help me!!!
I am sorry for possible English mistakes (I am not American)
I don't know if you can do it, but if you can one of the simplest way is by using GameComponents. Making your game as a GC enables you to launch multiples parts of it at one time, without having issues with threads.
As #eudabash mentioned in the comment section, you'll need to do the game.Run() in a seperate thread:
Game1 game = new Game1();
Thread thread = new Thread(() =>
{
game.Run();
};
thread.Start();
or, if you're on .Net 4.0 (I think. Or even 3.5)
Game1 game = new Game1();
Task.Factory.StartNew(() =>
{
game.Run();
}
Optionally make 'game' a field in your Form1 class, so you can access it anywhere. Just make sure to only retrieve data from Game, and never edit the UI from within Game. Cross-thread operations and whatnot. If you need to, remember to invoke.

How do I use Console.CancelKeyPress in .NET 4? (Works fine in .NET 3.5 and below)

I am writing a Console app in C# 4 and want to gracefully cancel my program and Ctrl + C is pressed. The following code I have used many times before, but now when trying to use it in .NET 4, it seems a strange unhandled exception is occurring.
namespace ConsoleTest
{
class Program
{
private static bool stop = false;
static void Main(string[] args)
{
System.Console.TreatControlCAsInput = false;
System.Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
while (!stop)
{
System.Console.WriteLine("waiting...");
System.Threading.Thread.Sleep(1000);
}
System.Console.WriteLine("Press any key to exit...");
System.Console.ReadKey(true);
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
stop = true;
e.Cancel = true;
}
}
}
If I change the Target Framework to .NET 3.5, it works.
EDIT: It seems this person is seeing the same issue:
http://johnwheatley.wordpress.com/2010/04/14/net-4-control-c-event-handler-broken/
This is a known issue on Microsoft Connect.
Note that it does work outside of the debugger.
For a console application under VS2010 and .NET 4.0, i am using the following (not very clean) workaround:
in Project properties, under [Debug], check [Enable unmanaged code debugging];
during the startup code of your Program class, insert the following (this is .NET 2 style, use lambdas at your discretion):
Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
{
if (e.SpecialKey == ConsoleSpecialKey.ControlC)
{
e.Cancel = true; // tell the CLR to keep running
}
else if (e.SpecialKey == ConsoleSpecialKey.ControlBreak)
{
//e.Cancel = true; // "Applications are not allowed to cancel the ....
}
// do whatever you must to inform threads on application exit, etc
}
Although not obvious, this code will allow you to debug your CTRL-C handler like so:
start your program under the debugger (F5);
make sure your program's console has the focus;
press ctrl+pause (on my latitude e6500, i need to hold ctrl and Fn and F12);
The debugger will ask you about this interruption, click [Ignore] and you will find yourself in the handler (make sure a breakpoint was set)
THE SAME code will execute if ctrl+c is pressed, the only difference is you must set e.Cancel to true.
As pointed out by everybody else, the problem DOES NOT exist at runtime, this workaround is ONLY for stepping through the handler.

Categories

Resources