Please in my code i try to catch win32.systemevents.sessionended event to procede with saving of my app data by the end of session in case the app is not closed manually .. some time ago this has been workin and now that i had my project grown a lil it is not any more..? i have tried to find something meaningfull for few days but found nothing really.. when i try to catch another systemevent like MonitorResolutionChanged it works well but this one not. I have also tried to register within the mainWindow (app form ..), nothing :-( Please any idea?
I think all the relevant information should be in the beginning till void Main but i put it all in case you would need or want to see more .. Thanx a lot Tomas
My code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using MovablePython; // my own class within this project
using Avn; //my own referenced assembly
namespace DirDist
{
class Program
{
private static string appGuid = "Cddbserviceman";
private static System.Windows.Forms.ContextMenu nIMenu;
internal static System.Windows.Forms.NotifyIcon notifyIcon1;
private static MenuItem showItem;
public static MenuItem justCDsItem;
private static MenuItem searchItem;
private static MenuItem settingsItem;
private static MenuItem quitItem;
internal static Form1 mainWindow;
private static Hotkey hk;
internal static Registration.LicenceState mode; // app mode - registered/trial/blocked/demaged ..
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
using (Mutex mutex = new Mutex(false, appGuid))
{
if (!mutex.WaitOne(0, false))
{
MessageBox.Show("CDDB is already running on your machine \n (Check status bar for access ..)");
return;
}
GC.Collect();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
mode = Registration.Startup();
Program.mainWindow = new Form1();
mainWindow.Activate();
//mainWindow.Validate();
//mainWindow.Update();
mainWindow.Visible = false;
PutIcon();
//Microsoft.Win32.SystemEvents.SessionEnded += SystemEvents_SessionEnded;
Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);//**zkousime zda funguje pro hibernaci ..
RegisterHotKey(true);
Application.Run();
}
}
static void SystemEvents_SessionEnded(object sender, Microsoft.Win32.SessionEndedEventArgs e)
{
//MessageBox.Show("SessionEnded fired");
RegisterHotKey(false);
notifyIcon1.Visible = false;
notifyIcon1.Dispose();
notifyIcon1 = null;
if (!mainWindow.dBSaved) mainWindow.SaveDb(Form1.settings.dBPath);
if (mainWindow.index != null) mainWindow.SaveIndex(Form1.settings.indexPath);
Microsoft.Win32.SystemEvents.SessionEnded -= new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);
mainWindow.Close();
}
// zaregistruje globalni hotkey ctrl+shift+F Pro hledani
private static void RegisterHotKey(bool active)
{
if (!active)
{
if (hk != null) hk.Unregister();
}
else
{
if(hk ==null) hk = new Hotkey();
hk.KeyCode = Keys.F;
//hk.Windows = true;
hk.Shift = true;
hk.Control = true;
//hk.Pressed += delegate { Console.WriteLine("Windows+1 pressed!"); };
hk.Pressed += delegate { searchItemClick(new object(), new EventArgs()); };
if (hk.GetCanRegister(mainWindow)) hk.Register(mainWindow);
else ; // just do nothing
}
}
private static void PutIcon()
{
if (notifyIcon1 == null)
{
showItem = new MenuItem ("&Show interface", new System.EventHandler (showInfaceClick));
justCDsItem = new MenuItem ("&Jus'CDs",new System.EventHandler ( justCDsClick));
justCDsItem.Checked = Form1.settings.justCDs;
searchItem = new MenuItem("Search CDDB",new System.EventHandler (searchItemClick));
searchItem.Shortcut = Shortcut.CtrlShiftF;
searchItem.ShowShortcut = true;
settingsItem = new MenuItem("Settings", new System.EventHandler(settingsItemClick));
quitItem = new MenuItem("&Quit", new System.EventHandler(quitItemClick));
nIMenu = new System.Windows.Forms.ContextMenu(new MenuItem[5] { showItem, justCDsItem, searchItem,settingsItem, quitItem });
notifyIcon1 = new System.Windows.Forms.NotifyIcon();
notifyIcon1.ContextMenu = nIMenu;
notifyIcon1.Icon = new System.Drawing.Icon(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Icon1.ico");
//notifyIcon1.Icon = new System.Drawing.Icon(System.IO.Path.GetDirectoryName(
//System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Icon1.ico");
//notifyIcon1.Icon = new System.Drawing.Icon("Icon1.ico");
notifyIcon1.DoubleClick += new EventHandler(notifyIcon1_DoubleClick);
notifyIcon1.Visible = true;
}
}
/* private static void notifyIcon1_MouseMove(object sender, MouseEventArgs mea)
* aby to fungovalo je treba upravit contextmenu na contextmenustrip a taky ty items .. az nakonec
* je tu kolem uz rozdelana priprava ..
{
notifyIcon1.ShowBalloonTip(2000,AppName,"Active",ToolTipIcon.None);
} */
// clicks on NotificationIcon context menu ..
private static void showInfaceClick(object sender, EventArgs e)
{
mainWindow.tabControl1.SelectedIndex = 0;
mainWindow.Show();
}
private static void justCDsClick(object sender, EventArgs e)
{
Form1.settings.justCDs = mainWindow.checkBox1.Checked = justCDsItem.Checked = !Form1.settings.justCDs;
if (mainWindow.Visible) mainWindow.Update();
}
private static void searchItemClick(object sender, EventArgs e)
{
mainWindow.tabControl1.SelectedIndex = 1 ;
//this.Size = new Size(this.Width, SystemInformation.PrimaryMonitorSize.Height);
mainWindow.Location = new System.Drawing.Point(SystemInformation.PrimaryMonitorSize.Width - mainWindow.Width, SystemInformation.PrimaryMonitorSize.Height - mainWindow.Height);
//mainWindow.Location = new System.Drawing.Point(880, 500);
mainWindow.Show();
}
private static void settingsItemClick(object sender, EventArgs e)
{
mainWindow.tabPage3_GotFocus(new Object(), new EventArgs());
mainWindow.tabControl1.SelectedIndex = 2;
mainWindow.Show();
}
public static void quitItemClick(object sender, EventArgs e)
{
if (DialogResult.Cancel == MessageBox.Show("Really exit application and stop scanning?",Form1.AppName,MessageBoxButtons.OKCancel,MessageBoxIcon.Question)) return;
if (!mainWindow.dBSaved) mainWindow.SaveDb(Form1.settings.dBPath);
//if (mainWindow.index != null) mainWindow.SaveIndex(Form1.settings.indexPath);
if (Form1.settings.fileIndex) mainWindow.SaveIndex(Form1.settings.indexPath);
mainWindow.Close();
mainWindow = null;
notifyIcon1.Visible = false;
Application.Exit();
}
static void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
//throw new NotImplementedException();
//if (!mainWindow.Visible) mainWindow.WindowState = FormWindowState.Normal; else mainWindow.WindowState = FormWindowState.Minimized;
//if (!mainWindow.Visible) mainWindow.Show(); else mainWindow.Hide();
if (!mainWindow.Visible) mainWindow.Visible = true; else mainWindow.Visible = false;
}
}
}
OK. So here is the catch and solution . In Windows it is not determined whether win32.systemevents.sessionended shall be risen or form.close() will be called first by operating system. moreover it seems that if form.close() is called first then sessionended is omited even though form is not closed and disposed due to canceling closing process. in my system this behaviour changed after i ran some registry cleaning software. anyway understanding this we have to take care of both possible scenarios.
1. catch win32.systemevents.sessionended (or sessionending) event whatever suits our needs better and be
.
.
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);
Program.mainWindow = new Form1();
mainWindow.Activate();
mainWindow.Visible = false;
PutIcon();
RegisterHotKey(true);
Application.Run();
}
}
public static void SystemEvents_SessionEnded(object sender, Microsoft.Win32.SessionEndedEventArgs e)
{
// do whatever needed and exit application ..
RegisterHotKey(false);
notifyIcon1.Visible = false;
notifyIcon1.Dispose();
notifyIcon1 = null;
if (!mainWindow.dBSaved) mainWindow.SaveDb(Form1.settings.dBPath);
if (mainWindow.index != null) mainWindow.SaveIndex(Form1.settings.indexPath);
Microsoft.Win32.SystemEvents.SessionEnded -= new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);
if (mainWindow != null)
{
mainWindow.Dispose();
mainWindow = null;
}
Application.Exit();
}
2. properly override form.OnClosing() because this is being called when form is closing either manually by user or by system when shuting down, loging off etc. or create hanler for main form.Closing:
public Form1()
{
this.Closing += new CancelEventHandler(this.Form1_Closing);
InitializeComponent();
}
private void Form1_Closing(Object sender, CancelEventArgs e)
{
if (systemShutdown) Program.SystemEvents_SessionEnded(this, new Microsoft.Win32.SessionEndedEventArgs(Microsoft.Win32.SessionEndReasons.SystemShutdown));
else
{
e.Cancel = true;
this.Hide();
}
}
just want to mention that message pump must be runnig in order to sessionended be risen. Application.run() accomplishes that.
in my case as you can see i had to dig even deeper as i had closing redirected just to hide the app not to close it ( i just hide the app to notification irea icon and close it manually when i need .. ) and so i had to use some kind of way to specify the situation when this is called because sender is unfortunatelly and unexpectedly always this ..?
this is done by overring WndProc and catching propper message .here you can listen pretty much to everything inside windows ( like disc inserted / removed )but it is hooked only to a form and implementation gets often not so simple as you have to manully define various values and structs and compare against those values .. other then that its pretty simple:
private static int WM_QUERYENDSESSION = 0x11;
private static bool systemShutdown = false;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg==WM_QUERYENDSESSION)
{
systemShutdown = true;
}
base.WndProc(ref m);
}
this was found here:
http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending.aspx
Thinking a bit further we can possibly omit point 1 as system shall probably always try to call mainForm.close() but i keep it as i can not be certain about windows behaviour once it runs those things in different order again .. and also it is the mainly suggested solution for reacting to system shut down ..
hope this is helpfull for someone. greets from prague tomas
Here is something that you could try
For a shutdown, override the OnShutdown method:
protected override void OnShutdown()
{
//your code here
base.OnShutdown();
}
For a logoff:
First, add an event handler to Microsoft.Win32.SystemEvents.SessionEnded in the Service Constructor:
public MyService()
{
InitializeComponent;
Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);
}
Then add the handler:
void SystemEvents_SessionEnded(object sender, Microsoft.Win32.SessionEndedEventArgs e)
{
//your code here
}
This should catch any ended session, including the console itself (the one running the services).
Related
In My case
I Try to start and stop explorer.exe But when I run below code I get an exception saying
"Cannot process request because the process has exited."
So How do I find The Explorer Window that opened and Close it from within the Program
And How do I trigger an event on When the opened explorer window is getting closed from outside of my program.
public partial class Form1 : Form
{
private readonly Process proc = new Process();
public Form1()
{
InitializeComponent();
button2.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
proc.StartInfo = new ProcessStartInfo {
FileName = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + "/explorer.exe",
Arguments = #"D:\",
UseShellExecute = false
};
proc.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
proc.Kill();
button1.Enabled = true;
button2.Enabled = false;
}
private void button3_Click(object sender, EventArgs e)
{
Process[] Findit = Process.GetProcessesByName("Explorer");
int a = Findit.Length;
}
}
I have solved for now the problem myself. (thnx Jimi for all the tips :-) )
Be aware the code presented is only to share my progress so far in solving the problem and is in no way complete. failproof crash resistant sanitized or whatever.
The example starts an Automation Event Handler that checks every WindowOpenedEvent for having class name CabinetWClass and Name ":D\"
If it finds it, it Stores The ProcessID and the NativeWindowHandle in an object of a customclass AutoEle Together with the representation for the AutomationElement.
This combination should present a sort of unique identifier for the Opened File Explorer window.
The code uses the same Automation Event Handler on every WindowClosedEvent
It tests if the AutoMationElement saved in autoele is still there on every WindowClosedEvent
if not the file explorer window must have been closed outside of the program.
To close the Window programmaticly
I use the Windows API functions:
SendMessage(); and use WM_CLOSE (set as a constant)
SendMessagege(Handle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
Button1 is available at start and when clicked opens a file browser on path D:\
Button 1 is getting disabled thenand button2 wil be enabled.
When either the opened browser window is close with Button2 OR from outside, the program
button 2 is disabled again and button1 enabled.
I am sure there are better ways and i look forward seeing some better code . I am just starting with this so everything is new :-)
using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Automation;
using System.Runtime.InteropServices;
namespace ExplorerOpenClose
{
//Class created to store a asomewhat unique identifier for the explorer window that opened (Combinaton ProcessID and NativeWindowHandle
public class AutoEle
{
public AutomationElement src;
public int ProcesId=0;
public int NativeWindowHandle=0;
}
public partial class Form1 : Form
{
private Process proc = new Process();
private AutoEle AutoEle = new AutoEle();
public Form1()
{
InitializeComponent();
button2.Enabled = false;
// Start a Automation EventHanlder on window open and window close
AutomationElement This = AutomationElement.RootElement.FindFirst(TreeScope.Subtree, Condition.TrueCondition);
RegisterForAutomationEvents(This);
}
// Button1 Opens a Explorer on path "D:\
private void button1_Click(object sender, EventArgs e)
{
proc.StartInfo = new ProcessStartInfo
{
FileName = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + "/explorer.exe",
Arguments = #"D:\",
UseShellExecute = false
};
proc.Start();
button1.Enabled = false;
button2.Enabled = true;
}
//With Button 2 Closes The browser that opened with Explorer on path "D:\
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = true;
button2.Enabled = false;
const UInt32 WM_CLOSE = 0x0010;
// Check That the Native WindowHandle is Still the one we found before belonging to the same process
// And close the Window
try
{
if (AutoEle.src.Current.ProcessId == AutoEle.ProcesId & AutoEle.src.Current.NativeWindowHandle == AutoEle.NativeWindowHandle)
{
SendMessage(new IntPtr(AutoEle.NativeWindowHandle), WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
AutoEle.ProcesId = 0;
AutoEle.NativeWindowHandle = 0;
}
}
catch (ElementNotAvailableException)
{
// The window was allready closed. which is strang that i would end up here because i check for that
}
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
Automation.RemoveAllEventHandlers();
base.OnFormClosed(e);
}
private void RegisterForAutomationEvents(AutomationElement targetControl)
{
AutomationEventHandler eventHandler = new AutomationEventHandler(OnWindowOpenOrClose);
Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, targetControl, TreeScope.Subtree,eventHandler);
Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, targetControl, TreeScope.Subtree, eventHandler);
}
private void OnWindowOpenOrClose(object src, AutomationEventArgs e)
{
// Make sure the element still exists. Elements
// can disappear before the event is processed.
AutomationElement sourceElement;
try
{
sourceElement = src as AutomationElement;
}
catch (ElementNotAvailableException)
{
return;
}
if (e.EventId == WindowPattern.WindowOpenedEvent)
{
try
{
// check if it is ClassName CabinetWClass and the drive D:\ is the name
if (sourceElement.Current.ClassName == "CabinetWClass" & sourceElement.Current.Name == #"D:\")
{
// FOUND !!!! return sourceElement.Current.ProcessId;
// NativeWindowHandle = new IntPtr(sourceElement.Current.NativeWindowHandle);
//ProcessId = Process.GetProcessById(sourceElement.Current.ProcessId);
//ProcessId = sourceElement.Current.ProcessId;
//ProcToKill.Exited += new EventHandler (myProcess_Exited);
AutoEle.ProcesId = sourceElement.Current.ProcessId;
AutoEle.NativeWindowHandle = sourceElement.Current.NativeWindowHandle;
AutoEle.src = sourceElement;
}
}
catch (ElementNotAvailableException)
{
}
return;
}
if (e.EventId == WindowPattern.WindowClosedEvent)
{
try
{
if (AutoEle.ProcesId > 0)
{
try
{ // Tis will provoke am exception if the process does not exist anymore which means it was closed :-)
if (AutoEle.src.Current.ProcessId == AutoEle.ProcesId & AutoEle.src.Current.NativeWindowHandle == AutoEle.NativeWindowHandle);
}
catch (ElementNotAvailableException)
{
AutoEle.ProcesId = 0;
AutoEle.NativeWindowHandle = 0;
Invoke(new MethodInvoker(() =>
{
button1.Enabled = true;
button2.Enabled = false;
}));
}
}
}
catch (ElementNotAvailableException)
{
}
return;
}
}
}
}
I've created a .net application that needs to be able to be used without an internet connection. This application uses the CefSharp C# library to embed my rails app in a windows form. Below is my Main() function which sets up the cefsharp settings
static void Main()
{
//For Windows 7 and above, best to include relevant app.manifest entries as well
Cef.EnableHighDPISupport();
//We're going to manually call Cef.Shutdown below, this maybe required in some complex scenarios
CefSharpSettings.ShutdownOnExit = false;
var cachePath = "cache";
if (!Directory.Exists(cachePath)) Directory.CreateDirectory(cachePath);
var settings = new CefSettings();
settings.CachePath = cachePath;
settings.LogFile = "f7chromium.log";
settings.BrowserSubprocessPath = #"x86\CefSharp.BrowserSubprocess.exe";
//Perform dependency check to make sure all relevant resources are in our output directory.
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
Debug.WriteLine("Starting");
host = MyServer.Run();
//var browser = new BrowserForm();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Console.ReadLine();
}
Code to initialize form
public partial class Form1 : Form
{
public ChromiumWebBrowser chromeBrowser;
private static string baseUrl = "https://goo.com/";
public void InitializeChromium()
{
var url = baseUrl;
chromeBrowser = new ChromiumWebBrowser(url);
// Add it to the form and fill it to the form window.
this.Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
}
public Form1()
{
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
Bounds = Screen.PrimaryScreen.Bounds;
InitializeComponent();
InitializeChromium();
HotkeyManager.Current.AddOrReplace("Close", Keys.F10, OnClose);
HotkeyManager.Current.AddOrReplace("Reset", Keys.F8, OnReset);
HotkeyManager.Current.AddOrReplace("Refresh", Keys.F5, OnRefresh);
HotkeyManager.Current.AddOrReplace("DevTools", Keys.F3, DevTools);
}
private void DevTools(object sender, HotkeyEventArgs e)
{
chromeBrowser.ShowDevTools();
}
private void OnReset(object sender, HotkeyEventArgs e)
{
var result = MessageBox.Show("Confirm reset all station data", "Confirm Reset", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK) chromeBrowser.Load(baseUrl + "/reset");
}
private void OnRefresh(object sender, HotkeyEventArgs e)
{
chromeBrowser.Reload();
}
private void OnClose(object sender, HotkeyEventArgs e)
{
var result = MessageBox.Show("Close application?", "Confirm Exit", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK)
{
Process.Start(#"C:\");
Process.Start(#"powershell.exe");
Close();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
}
Is it possible to launch the application without an internet connection similarly to how you can load sites in chrome from cache by enabling the show-page-copy button?
How can I say if a winform whas closed do ...?
bool isRunning = false;
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains("Notepad"))
{
isRunning = true;
break;
}
}
The code above always checks if the process exists but the code is slow for what I want it to do.So is there a way to check if the Notepad process was actually closed instead of always looping to see if its there?
You can use Win32_ProcessStopTrace which indicates that a process is terminated.
ManagementEventWatcher watcher;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
watcher = new ManagementEventWatcher("Select * From Win32_ProcessStopTrace");
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Start();
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
if ((string)e.NewEvent["ProcessName"] == "notepad.exe")
MessageBox.Show("Notepad closed");
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
watcher.Stop();
watcher.Dispose();
base.OnFormClosed(e);
}
Don't forget to add a reference to System.Management and add using System.Management;
Note
If you want to monitor closing of an specific instance of notepad which you know, you can use such criteria:
if ((UInt32)e.NewEvent["ProcessID"]==knownProcessId)
If you want to check if any instance of notepad is open, you can use such criteria:
if (System.Diagnostics.Process.GetProcessesByName("notepad").Any())
The EventArrived will raise in a different thread than UI thread and if you need to manipulate UI, you need to use Invoke.
Above method notifies you about closing of all processes, regardless of the time they are opened, before or after your application run. If you don't want to notified about the processes which may be opened after your application starts, you can get existing notepad processes and subscribe to their Exited event:
private void Form1_Load(object sender, EventArgs e)
{
System.Diagnostics.Process.GetProcessesByName("notepad").ToList()
.ForEach(p => {
p.EnableRaisingEvents = true;
p.Exited += p_Exited;
});
}
void p_Exited(object sender, EventArgs e)
{
MessageBox.Show("Notepad closed");
}
This should do the trick. It will create a event for you when the process dies. No need to loop through all the process.
public static event EventHandler ProcessDied;
public void CheckForProcess()
{
InitializeComponent();
ProcessDied += new EventHandler(Process_Died);
AttachProcessDiedEvent("notepad", ProcessDied);
}
private void AttachProcessDiedEvent( string processName,EventHandler e )
{
Process isSelectedProcess=null;
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains(processName))
{
isSelectedProcess = clsProcess;
break;
}
}
if(isSelectedProcess!=null)
{
isSelectedProcess.WaitForExit();
}
if(e!=null)
{
e.Invoke(processName, new EventArgs());
}
}
private void Process_Died(object sender, EventArgs e)
{
//Do Your work
}
Let me know if there are any issues.
you can do it without looping but dont know if its much faster :
bool isRunning = Process.GetProcessesByName("NotePad").FirstOrDefault() != null;
or
bool isRunning = Process.GetProcessesByName("notepad").Any();
I got this from here Check if a specific exe file is running
I have a class SendCountingInfo() and it will send a message to server every 5 minutes. The code inside this class are:
public void StartSendCountingInfo()
{
DoStartSendCountingInfo(300000);
}
private void DoStartSendCountingInfo(int iMiSecs)
{
_pingTimer = new System.Timers.Timer(iMiSecs);
_pingTimer.Elapsed += new System.Timers.ElapsedEventHandler(pingTimer_Elapsed);
_pingTimer.Start();
}
void pingTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
PingRemoteHost();
}
When I try to call it in the Windows Form class, it didn't work.
But, when I remove the timer and call PingRemoteHost() directly, it works. However, the form didn't load properly. It shows blank screen but the method PingRemoteHost() work.
Here is the code inside the windows form:
private void Layout_Load(object sender, EventArgs e)
{
tSystemChecker = new System.Timers.Timer(1000);
tSystemChecker.Elapsed += new System.Timers.ElapsedEventHandler(tSystemChecker_Elapsed);
tSystemChecker.Start();
this.WindowState = FormWindowState.Maximized;
}
void tSystemChecker_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
UIThreadWork(this, delegate
{
try
{
SuspendLayout();
DoCheckHardwareStatus();
DoCheckLanguage();
SendCountingInfo sci = new SendCountingInfo();
sci.StartSendCountingInfo();
}
catch (Exception exp)
{
System.Diagnostics.Debug.WriteLine(exp.Message);
System.Diagnostics.Debug.WriteLine(exp.Source);
System.Diagnostics.Debug.WriteLine(exp.StackTrace);
}
ResumeLayout(true);
});
}
Do you have any idea what's wrong?
Use a thread and see if the problem persist
using System.Threading;
//Put this where you want to start the first timer
Thread thread = new Thread(dowork =>
{
public void StartSendCountingInfo();
}
If you are updating the GUI use for your controls
guicontrol.BeginInvoke((MethodInvoker)delegate()
{
guicontrol.Text = "aa";
//etc
});
I have a WPF application into which I'm adding some top level, catch all error handling. I handle the DispatcherUnhandledException event like so:
private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (_isHandlingError)
{
_log.Error("Critical unhandled error", e.Exception);
e.Handled = true;
return;
}
_isHandlingError = true;
var vm = _windsorContainer.Resolve<ErrorReporterViewModel>();
Dispatcher.Invoke(() =>
{
vm.Details = FailureMessageBuilder.CreateContent(e.Exception);
var view = new ErrorReporterView { DataContext = vm };
view.Show();
});
e.Handled = true;
NotifyOfException(e.Exception, vm.Description);
_isHandlingError = false;
}
The problem is, that the call to Show() (or ShowDialog) never returns, and the error dialog is never shown.
What might be the issue?
Do you have attached your event to the Application?
cApp.Dispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(Dispatcher_UnhandledException);
cApp.InitializeComponent();
cApp.Run(new MainWindow());
And then
private static void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
...e.Exception.Message
}