C#写字板问题一二 —— C#+WinForm编程趣味入门实战-天轰穿.NET4趣味编程视频教程
(1)[WinForm]Application.Exit關閉應用程式後真的不執行了嗎?
結論:
Application.Exit:會通知應用程式停止相關的訊息(all threads),並等待訊息執行完成後關閉應用程式(all UI),
但這只保證訊息是在Application.Exit前才能被停止,Application.Exit後的訊息是無法被停止的,
所以後續工作仍會佔用系統資源,直到相關工作結束為止。
Application.ExitThread:結束目前執行緒的訊息迴圈,並關閉執行緒上的所有視窗,所以不會引發Form.Closed和Form.Closing事件。
Environment.Exit:不等待相關訊息的結束,強制退出應用程式。
所以個人認為,正確的退出應用程式,應在Form.Closing事件中循環處理停止每個訊息工作,
並在Form.Closed事件中加入Environment.Exit會來的比較保險點。
1 //关闭窗体 2 #region 关闭窗体 3 private void Form1_FormClosing(object sender, FormClosingEventArgs e) 4 { 5 string msg = "有内容,但未保存,是否保存"; 6 7 if (save == false) 8 { 9 if (richTextBox1.Text != "") 10 { 11 if (flag == true) 12 { 13 //1.-----------------------------------------------> 14 switch (MessageBox.Show(msg, "警告", MessageBoxButtons.YesNoCancel)) 15 { 16 case DialogResult.Yes: //选择“是” 17 if (SaveFile()) 18 { 19 Application.ExitThread(); 20 } 21 break; 22 case DialogResult.No: 23 e.Cancel = false; 24 break; 25 case DialogResult.Cancel: 26 e.Cancel = true; 27 break; 28 } 29 30 //1.-------------------------------------------------> 31 } 32 33 } 34 } 35 if (save == true) 36 { 37 if (richTextBox1.Text != "") 38 { 39 if (flag == true) 40 { 41 msg = "将更改保存到" + filePath; 42 //2.-----------------------------------------------> 43 switch (MessageBox.Show(msg, "警告", MessageBoxButtons.YesNoCancel)) 44 { 45 case DialogResult.Yes: //选择“是” 46 if (SaveFile()) 47 { 48 Application.ExitThread(); 49 } 50 break; 51 case DialogResult.No: 52 e.Cancel = false; 53 break; 54 case DialogResult.Cancel: 55 e.Cancel = true; 56 break; 57 } 58 59 //2.-------------------------------------------------> 60 } 61 62 } 63 } 64 } 65 #endregion
(2) 查找按钮
1 #region 查找按钮 2 3 private void Search_Click(object sender, EventArgs e) 4 { 5 if (FindMyText(tb_txt.Text.Trim(), indexToText) == -1) 6 { 7 MessageBox.Show("已经完成搜索文档。", "提示"); 8 9 indexToText = 0; 10 } 11 } 12 13 public int FindMyText(string text, int start) 14 { 15 //初始化默认的返回值为false。 16 int returnValue = -1; 17 18 // 确保已经指定一个搜索字符串和一个有效的起始点. 19 if (text.Length > 0 && start >= 0) 20 { 21 if (start != richTextBox1.Text.Length) 22 { 23 // 获得搜索字符串的位置在richTextBox1. 24 indexToText = richTextBox1.Find(text, start, RichTextBoxFinds.MatchCase); 25 26 // 确定文本被发现在richTextBox1. 27 if (indexToText >= 0) 28 { 29 returnValue = indexToText; 30 indexToText += 1; 31 } 32 } 33 } 34 return returnValue; 35 } 36 37 #endregion
作者:【唐】三三
出处:https://www.cnblogs.com/tangge/archive/2013/02/26/2933800.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具