[英]WPF app.xaml exit event not working
i'm not a pro wpf user so i came here to ask you for help. 我不是专业的WPF用户,所以我来这里向您寻求帮助。 I want to update some DB value when the apps exit but nothing happen. 我想在应用程序退出但没有任何反应时更新一些数据库值。 here is my app.xaml code: 这是我的app.xaml代码:
<Application x:Class="pcAdmin.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:pcAdmin"
Startup="Application_Startup" Exit="Application_Exit"
>
<Application.Resources>
</Application.Resources>
</Application>
and here is the code behind of the Application_Exit methode: 这是Application_Exit方法的背后代码:
private void Application_Exit(object sender, ExitEventArgs e)
{
//just for verification
System.Windows.Forms.MessageBox.Show("apps is shutting down");
//updating DB
conDB = new MySQLConnect(this.connexion_string);
conDB.connectDB();
conDB.updateStatus("OFF", IP.mac);
conDB.disconnect();
pw.requestStop();
}
NB:- there are no error with all the fonction in the application_exit because they work fine in other part of the program. 注意:-application_exit中的所有功能都没有错误,因为它们可以在程序的其他部分正常工作。 - the apps doesn't have window so i can't use windows_closing or windows_closed event (but tryed it with them and the code work) I'll appreciate greatly your help. -这些应用程序没有窗口,因此我无法使用windows_closing或windows_closed事件(但尝试使用它们和代码可以工作),我将非常感谢您的帮助。 Thank you 谢谢
Here is the full code of the app.xaml code behind 这是app.xaml代码的完整代码
public partial class App : System.Windows.Application
{
private string pData;
private string pDataPath;
private NotifyIcon nIcon;
private string connexion_string;
private string host;
private string user;
private string pwd;
private string base_sql;
private InfoPC IP;
private MySQLConnect conDB;
private IPChangeDetect ipc;
private ProcessWorker pw;
private Programme programme;
private Service services;
private List<Svc> sc;
private AV antivirus;
private Processor processor;
private void Application_Startup(object sender, StartupEventArgs e)
{
this.pData = "%ALLUSERSPROFILE%";
this.pDataPath = Environment.ExpandEnvironmentVariables(pData);
//chargement de l'icon dans la barre de tâche
nIcon = new NotifyIcon();
this.nIcon.Icon = new Icon(@"D:\sav Jerrys\pro\getInfo2.0\pcAdmin\pcAdmin\logo.ico");
nIcon.Visible = true;
nIcon.BalloonTipText = "Gathering PC info";
nIcon.BalloonTipTitle = "AEthernam";
nIcon.ShowBalloonTip(5000);
//mise à jour de l'application
getUpdated();
//obtention des paramètres de connexion à la base de donnée
recupParam();
//connexion à la base de donnée et envoi des information pendant le chargement de pcAdmin
connexion_string = "Server=" + this.host + ";Uid=" + this.user + ";password=" + this.pwd + ";database=" + this.base_sql + ";port=3306";
this.IP = new InfoPC();
IP.find_info();
conDB = new MySQLConnect(connexion_string, IP.mac, IP.ip, IP.domaine, IP.nom);
conDB.connectDB();
conDB.sendData();
//detection du changement d'ip après le chargement du logiciel
ipc = new IPChangeDetect(conDB);
ipc.detectIPChange();
conDB.disconnect();
//THread for listing process
pw = new ProcessWorker(connexion_string, IP.mac, pDataPath + @"\AEthernam\proc.bin");
Thread processThread = new Thread(pw.processWorker);
processThread.IsBackground = true;
processThread.Start();
while (!processThread.IsAlive) ;
//récupération de la liste des programmes
recupProg();
//récupération des services
recupService();
//récupération AV
recupAV();
//Recup info processeur
recupProcInfo();
//TODO:Recup info disque dur physique
recupPhyDiskInfo();
//TODO:Recup info partition
recupLogDiskInfo();
//TODO:Recup info Mémoire
recupMemoryInfo();
}
private void getUpdated()
{
// StreamWriter sw = new StreamWriter(pDataPath + "\\AEthernam\\aethernam.log");
Version appsVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
UpdateChecker upChecker = new UpdateChecker(appsVersion.ToString());
upChecker.checkUpdate();
//try
//{
// sw.WriteLine(upChecker.getLog);
//}
//catch(Exception ex)
//{
// this.log = "erreur ajout log dans le fichier log:\t" + ex.Message;
//}
}
private void recupParam()
{
try
{
StreamReader sr = new StreamReader(pDataPath + "\\AEthernam\\aethernam.cfg");
string ligne = sr.ReadLine();
this.host = ligne;
ligne = sr.ReadLine();
this.user = ligne;
ligne = sr.ReadLine();
this.pwd = ligne;
ligne = sr.ReadLine();
this.base_sql = ligne;
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
private void recupProg()
{
programme = new Programme();
List<prog> liste_programe = programme.recupProg();
conDB = new MySQLConnect(connexion_string, IP.mac);
conDB.connectDB();
if (System.IO.File.Exists(pDataPath + @"\AEthernam\prog.bin"))
{
List<prog> list_pro = programme.deserialize(pDataPath + @"\AEthernam\prog.bin");
if (list_pro.Count != liste_programe.Count)
{
//mise à jour de la base des programmes
conDB.update_Prog(IP.mac, liste_programe);
conDB.disconnect();
programme.serialize(list_pro, pDataPath + @"\AEthernam\prog.bin");
}
}
else
{
conDB.sendProg(liste_programe);
conDB.disconnect();
programme.serialize(liste_programe, pDataPath + @"\AEthernam\prog.bin");
}
}
private void recupService()
{
this.services = new Service();
sc = services.getSvc();
conDB = new MySQLConnect(connexion_string, IP.mac);
conDB.connectDB();
if (System.IO.File.Exists(pDataPath + @"\AEthernam\svc.bin"))
{
List<Svc> svcs = services.deserialize(pDataPath + @"\AEthernam\svc.bin");
if (svcs.Count != sc.Count)
{
//Mise à jour de la base des sevices
conDB.updateService(IP.mac, svcs);
conDB.disconnect();
services.serialize(svcs, pDataPath + @"\AEthernam\svc.bin");
}
}
else
{
//insertion des services dans la base
conDB.sendService(sc);
conDB.disconnect();
services.serialize(sc, pDataPath + @"\AEthernam\svc.bin");
}
}
private void recupAV()
{
List<AV> listAv = new List<AV>();
FindAv avInstallé = new FindAv();
ManagementObjectCollection avs = avInstallé.AvInstalled();
foreach (ManagementObject mo in avs)
{
antivirus = new AV();
antivirus.nom = mo["DisplayName"].ToString();
antivirus.etat = avInstallé.findState(mo["productState"].ToString());
listAv.Add(antivirus);
}
conDB = new MySQLConnect(connexion_string, IP.mac);
conDB.connectDB();
if (!System.IO.File.Exists(pDataPath + @"\AEthernam\prog.bin"))
{
foreach (AV av in listAv)
{
conDB.sendAV(av);
conDB.disconnect();
}
}
else
{
conDB.updateAV(IP.mac, listAv);
conDB.disconnect();
}
}
private void recupMemoryInfo()
{
List<Ram> liste_ram = new List<Ram>();
liste_ram = new RamInfo().getRams();
conDB = new MySQLConnect(connexion_string, IP.mac);
conDB.connectDB();
if (!System.IO.File.Exists(pDataPath + @"\AEthernam\prog.bin"))
{
conDB.sendRam(liste_ram);
conDB.disconnect();
}
else
{
conDB.updateRam(IP.mac, liste_ram);
conDB.disconnect();
}
}
private void recupPhyDiskInfo()
{
List<DisquePhysique> liste_pdisk = new List<DisquePhysique>();
liste_pdisk = new PhysicalDiskInfo().getPDisk();
conDB = new MySQLConnect(connexion_string, IP.mac);
conDB.connectDB();
if (!System.IO.File.Exists(pDataPath + @"\AEthernam\prog.bin"))
{
conDB.sendPhydisque(liste_pdisk);
conDB.disconnect();
}
else
{
conDB.updatePhydisque(IP.mac, liste_pdisk);
conDB.disconnect();
}
}
private void recupLogDiskInfo()
{
List<LogicalDisk> liste_ldisk = new List<LogicalDisk>();
liste_ldisk = new LogicalDiskInfo().getPartition();
conDB = new MySQLConnect(connexion_string, IP.mac);
conDB.connectDB();
if (!System.IO.File.Exists(pDataPath + @"\AEthernam\prog.bin"))
{
conDB.sendLdisque(liste_ldisk);
conDB.disconnect();
}
else
{
conDB.updateLdisque(IP.mac, liste_ldisk);
conDB.disconnect();
}
}
private void recupProcInfo()
{
processor = new Processor();
ProcessorInfo pInfo = new ProcessorInfo();
processor = pInfo.getInfo();
conDB = new MySQLConnect(connexion_string, IP.mac);
conDB.connectDB();
if (!System.IO.File.Exists(pDataPath + @"\AEthernam\prog.bin"))
{
conDB.sendProcessor(processor);
conDB.disconnect();
}
else
{
conDB.updateProcessor(IP.mac, processor);
conDB.disconnect();
}
}
private void Application_Exit(object sender, ExitEventArgs e)
{
System.Windows.Forms.MessageBox.Show("apps is shutting down");
conDB = new MySQLConnect(this.connexion_string);
conDB.connectDB();
conDB.updateStatus("OFF", IP.mac);
conDB.disconnect();
pw.requestStop();
}
}
I have a feeling the problem is related to the thread you have. 我感觉到问题与您拥有的线程有关。 If it's a foreground thread it is not allowing the application to exit until it's running. 如果它是前台线程 ,则它不允许应用程序在运行之前退出。 And since you are trying to stop it in the Exit_Application method, that's never happening. 并且由于您试图在Exit_Application方法中停止它,所以这永远不会发生。 Try setting somewhere where you are creating the thread. 尝试在创建线程的地方进行设置。
pw.IsBackground = true;
If you are using new Thread() to create it, it always default's to foreground thread. 如果使用new Thread()创建它,则它始终默认为前台线程。
UPDATE: 更新:
Since the application is closing from the Task Manager, the process is simply killed by windows and there is no way to execute some code before it closes. 由于应用程序是从“任务管理器”中关闭的,因此该进程只是被Windows杀死,无法在关闭之前执行某些代码。 Check this answer for a workaround, involving DB. 检查此答案以获取一种解决方法,涉及数据库。 Or you would need some UI or a tray icon at least, that will allow you closing the application gracefully on some button click. 或者,您至少需要一些UI或任务栏图标,这使您可以在单击某些按钮时优雅地关闭该应用程序。 To gracefully close the application you can use previously suggested: 要正常关闭应用程序,可以使用以前建议的方法:
Application.Current.Shutdown();
Just do the following: 只需执行以下操作:
private void Application_Startup(object sender, StartupEventArgs e)
{
//your current code
Application.Current.Shutdown();
}
this should trigger the Exit method of your application and run the code within the application_exit(); 这应该触发您应用程序的Exit方法并在application_exit()中运行代码;
Thank you all for your answer and help, I'll put @3615 answer as an acceptable solution for me. 谢谢大家的答复和帮助,我将@ 3615答复作为对我来说可以接受的解决方案。 I'll gona find some way to see if user killed process then update my DB accordingly 我将找到某种方法来查看用户是否杀死了进程,然后相应地更新了我的数据库
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.