I have C# application and can monitoring Logoff and SystemShutdown events
class Program
{
static void Main(string[] args)
{
SystemEvents.SessionEnding += SystemEvents_SessionEnding;
Console.ReadLine(); //This is needed to keep the application running.
}
static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
switch (e.Reason)
{
case SessionEndReasons.Logoff:
MessageBox.Show("User logging off");
break;
case SessionEndReasons.SystemShutdown:
MessageBox.Show("System is shutting down");
break;
}
}
}
please help me , how I can monitor (get event) user Logon event?
thank you
Assuming you are running as windows service you should use SessionSwitch handler for logon session.
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if(e.Reason==SessionSwitchReason.SessionLogon)
{
}
}
probably you should use SessionSwitch event:
static void Main(string[] args)
{
SystemEvents.SessionEnding += SystemEvents_SessionEnding;
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
Console.ReadLine(); //This is needed to keep the application running.
}
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
switch (e.Reason)
{
case SessionSwitchReason.SessionLogon:
//do something
break;
}
}
Related
I want to handle all unexpected errors in a WPF application. When I look at, there are different events for different situation to capture and control error. Also I added these in application constructor method
public App()
{
AppDomain.CurrentDomain.FirstChanceException += OnFirstChanceException;
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
Dispatcher.UnhandledException += OnDispatcherUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
}
However, I try that for checking handling but they didn't work. What is the reason?
private void btnStart_Click(object sender, RoutedEventArgs e) //2021112242
{
throw new StackOverflowException();
}
Every exception event has his own callback method & event object
// Dispatcher.UnhandledException
private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
}
// TaskScheduler.UnobservedTaskException
private static void OnTaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
}
// AppDomain.CurrentDomain.UnhandledException
private static void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
}
// AppDomain.CurrentDomain.FirstChanceException
private static void OnCurrentDomainUnhandledException(object sender, FirstChanceExceptionEventArgs e)
{
}
App has an event for this called DispatcherUnhandledException. This works in most cases but when the exception is thrown from a separate thread it gets a little hairy.
public partial class App
{
public App()
{
// Globally handle errors/exceptions for a friendly close.
DispatcherUnhandledException += DispatcherOnUnhandledException;
}
private void DispatcherOnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
try
{
e.Handled = true;
e.Exception.Display("An unhandled exception occurred, the application will now close.");
e.Exception.Log(); // log the problem.
Shutdown(-1); // assume not recoverable.
}
catch
{
Shutdown(-1);
}
}
}
what i have tried is?
Window.Current.CoreWindow.PointerMoved += OnCorePointerMoved1;
Window.Current.CoreWindow.PointerMoved += OnCorePointerMoved2;
private void OnCorePointerMoved1(CoreWindow sender, PointerEventArgs args)
{
args.Handled = true;
}
private void OnCorePointerMoved2(CoreWindow sender, PointerEventArgs args)
{
}
when i run the code,the PointreMoved1 Event is triggered first.In that ,I had handled e.Handled=true .And then why PointerMoved2 Event also triggered.I don't know why this is happening?
Right I have the following code:
public partial class Form1 : Form
{
delegate void UpdateUI();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (!Fiddler.CertMaker.rootCertExists())
{
if (!Fiddler.CertMaker.createRootCert())
{
throw new Exception("Unable to create cert for FiddlerCore.");
}
}
if (!Fiddler.CertMaker.rootCertIsTrusted())
{
if (!Fiddler.CertMaker.trustRootCert())
{
throw new Exception("Unable to install FiddlerCore's cert.");
}
}
Fiddler.FiddlerApplication.OnNotification += delegate (object snder, NotificationEventArgs oNEA) { MessageBox.Show("** NotifyUser: " + oNEA.NotifyString); };
Fiddler.FiddlerApplication.Log.OnLogString += delegate (object snder, LogEventArgs oLEA) { MessageBox.Show("** LogString: " + oLEA.LogString); };
Fiddler.FiddlerApplication.AfterSessionComplete += FiddlerApplication_OnAfterSessionComplete;
Fiddler.FiddlerApplication.Startup(0, FiddlerCoreStartupFlags.Default & FiddlerCoreStartupFlags.DecryptSSL);
}
void FiddlerApplication_OnAfterSessionComplete(Session oSession)
{
if(oSession.fullUrl.Contains("google.com"))
richTextBox1.Invoke(new UpdateUI(() =>
{
richTextBox1.AppendText(oSession.GetResponseBodyAsString());
}));
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Fiddler.FiddlerApplication.Shutdown();
}
}
The thing is with DecryptSSL flag set on startup the on aftersesssion complete never fires, I also never get any messages from either the notification or logs callbacks.
Any ideas?
I think port 0 might be a problem in the Startup(), I tried with port 8888:
Fiddler.FiddlerApplication.Startup(8888, FiddlerCoreStartupFlags.Default & FiddlerCoreStartupFlags.DecryptSSL);
I tried with these before response and before request handlers instead of OnAfterSessionComplete. In your Form1_Load():
Fiddler.FiddlerApplication.BeforeRequest += new SessionStateHandler(HandleBeforeRequest);
Fiddler.FiddlerApplication.BeforeResponse += new SessionStateHandler(HandleBeforeResponse);
And the handlers:
private void HandleBeforeRequest(Session oSession)
{
oSession.bBufferResponse = true;
}
private void HandleBeforeResponse(Session oSession)
{
if(oSession.fullUrl.Contains("google.com"))
{
richTextBox1.Invoke(new UpdateUI(() =>
{
richTextBox1.AppendText(oSession.GetResponseBodyAsString());
}));
}
}
By the way, don't know if you omitted them from your sample but I needed to add these in the constructor:
Load += Form1_Load;
FormClosing += Form1_FormClosing;
Might also be good to add this before Shutdown():
FiddlerApplication.oProxy.Detach();
I have a form to ask for some data. At leaving of an input field (TextBox, DGV) the appropriate _Validating methode or _CellValueChanged methode is called.
If I want to end the program this methode is called, too - before the _FormClosing methode is called.
How can I fin out whether the program branches into the _FormClosing methode or not?
private void txb_Validating(object sender, CancelEventArgs e)
{
doLog("Text 1");
}
private void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
doLog("Text 2");
}
private void doLog(string txt)
{
// this is first called at closing...
if( [FormClosing is active] )
{
// Do something
}
else
{
// Do someting different
}
}
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
// ... and this but later
// Write the Logfile
}
How have I to replace [FormClosing is active] to get to the right result?
I tried so
if ( this.FormClosing== true )
and so
this.FormClosing +=new FormClosingEventHandler(MyForm_FormClosing);
and so
FormClosingEventHandler cl = new FormClosingEventHandler(MyForm_FormClosing);
but I always was in a dead end.
This would do the trick:
public class YourForm : Form
{
private bool bIsClosing = false;
public YourClass()
{
InitializeComponent();
this.FormClosing +=
new FormClosingEventHandler(MyForm_FormClosing);
}
private void txb_Validating(object sender, CancelEventArgs e)
{
doLog("Text 1");
}
private void dgv_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
doLog("Text 2");
}
private void doLog(string txt)
{
// this is first called at closing...
if( bIsClosing )
{
// Do something
}
else
{
// Do someting different
}
}
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
bIsClosing = true;
// Write the Logfile
doLog("whatever");
}
}
this.FormClosing is an event that gets triggered once your form starts closing (like clicking the close button), hence the name. You need your application to register that event like so:
this.FormClosing +=new FormClosingEventHandler(MyForm_FormClosing);
This insures that once the FormClosing event gets triggered, your MyForm_FormClosing will be called.
You can create a flag like bool bIsFormClosing and set that flag once your closing function get called.
Edit:
As I understand now by reviewing your answer and your comments, you want to know in your doLog function if the form is closing.
Here is another approach
`
public class YourForm : Form
{
private bool bIsClosing = false;
Private bool bClosingHandled = false;
public YourClass()
{
InitializeComponent();
this.FormClosing +=
new FormClosingEventHandler(MyForm_FormClosing);
}
private void txb_Validating(object sender, CancelEventArgs e)
{
doLog("Text 1");
}
private void dgv_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
doLog("Text 2");
}
private void doLog(string txt)
{
// this is first called at closing...
if( bIsClosing )
{
// Do something
bClosingHandled = true;
this.close();
}
else
{
// Do someting different
}
}
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
If(!bClosingHandled)
{
bIsClosing = true;
e.Cancel = true;
return;
}
// Write the Logfile
doLog("whatever");
}
}`
This approach uses two flags... When you first receive a close event, you set the bIsClosing flag to true, cancels the event and return. Then once your dolog function get called, you force the close operation.
I have a console application in C#. If something goes wrong, I call Environment.Exit() to close my application. I need to disconnect from the server and close some files before the application ends.
In Java, I can implement a shutdown hook and register it via Runtime.getRuntime().addShutdownHook(). How can I achieve the same in C#?
You can attach an event handler to the current application domain's ProcessExit event:
using System;
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += (s, e) => Console.WriteLine("Process exiting");
Environment.Exit(0);
}
}
Hook AppDomain events:
private static void Main(string[] args)
{
var domain = AppDomain.CurrentDomain;
domain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
domain.ProcessExit += new EventHandler(domain_ProcessExit);
domain.DomainUnload += new EventHandler(domain_DomainUnload);
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
Console.WriteLine("MyHandler caught: " + e.Message);
}
static void domain_ProcessExit(object sender, EventArgs e)
{
}
static void domain_DomainUnload(object sender, EventArgs e)
{
}
I'd recommend wrapping the call to Environment.Exit() in your own method and using that throughout. Something like this:
internal static void MyExit(int exitCode){
// disconnect from network streams
// ensure file connections are disposed
// etc.
Environment.Exit(exitCode);
}