前言
之前有个需求就是监听文件夹中最新的txt文档获取最新数据,还有其他功能,
比如:开机自启动、只在任务管理器关闭、阻止ctrl+c中断等,对此作个记录,整理代码。
一、监听txt文档增加数据
代码如下:
static void runmainlogic() { //1. 获取程序基目录 string basedir = appdomain.currentdomain.basedirectory; //2.拼接相对路径(目标路径 - 文件夹)并转换为绝对路径 string relativepath = @"..\..\..\..\totaltest\debug"; string targetdir = path.getfullpath(path.combine(basedir, relativepath)); //3.检查目标目录是否存在 if (!directory.exists(targetdir)) { console.writeline("目标目录不存在:{" + targetdir + "}"); return; } //4.获取所有名称包含“test”的子文件夹,并按时间排序 var latsettestdir = directory.getdirectories(targetdir, "*test*", searchoption.topdirectoryonly) .select(dir => new directoryinfo(dir)) .orderbydescending(dir => dir.lastwritetime) .firstordefault(); if (latsettestdir == null) { console.writeline("test文件夹路径不存在!"); return; } string folderpath = latsettestdir.fullname; string str = "开始监控文件夹: {" + folderpath + "}"; console.writeline(str); //txt文档监听 textfilewatcher watcher = new textfilewatcher(folderpath); //先被执行 watcher.datareceived += ondatareceived; //订阅事件 watcher.setnewestfileastarget(); } //订阅事件 static void ondatareceived(object sender, string data) { string strline = data; //需要的数据 }
二、其他功能
1. 设置开机自启动
代码如下:
static void setautostart(string appname, string apppath) { registrykey key = registry.currentuser.opensubkey("software\\microsoft\\windows\\currentversion\\run", true); key.setvalue(appname, apppath); key.close(); }
作用:将程序添加到注册表启动项,实现开机自动运行。
调用方式:
setautostart("myconsoleapp", system.reflection.assembly.getexecutingassembly().location);
2. 禁止控制台窗口关闭按钮
代码如下:
[dllimport("user32.dll")] private static extern intptr getsystemmenu(intptr hwnd, bool brevert); [dllimport("user32.dll")] private static extern bool enablemenuitem(intptr hmenu, uint uidenableitem, uint uenable); private const uint sc_close = 0xf060; private const uint mf_grayed = 0x00000001; static void disableclosebutton() { intptr hwnd = system.diagnostics.process.getcurrentprocess().mainwindowhandle; intptr hmenu = getsystemmenu(hwnd, false); enablemenuitem(hmenu, sc_close, mf_grayed); }
作用:禁用窗口的x关闭按钮,用户无法直接关闭程序。
3. 阻止ctrl + c中断
代码如下:
console.cancelkeypress += (sender, e) => e.cancel = true;
作用:防止用户按 ctrl + c 终止程序。
4. 防止程序退出(无限循环)
代码如下:
while(true) { thread.sleep(1000); //防止cpu占用过高 }
作用:让程序无限运行,除非任务管理器终止或程序报错。
总结
如将开机自启动和只能在任务管理器关闭放到监听txt文档功能。
在主函数中,代码如下:
//1. 设置开机自启动 setautostart("consoleapplication1", system.reflection.assembly.getexecutingassembly().location); //2. 禁用关闭按钮 disableclosebutton(); //3. 阻止ctrl+c 关闭 console.cancelkeypress += (sender, e) => { e.cancel = true; // 阻止默认行为 console.writeline("ctrl+c 被禁用,无法关闭程序。"); }; //4. 主要业务逻辑 runmainlogic(); //5. 防止程序退出(无限循环) while (true) { thread.sleep(1000); // 每秒钟检查一次(防止 cpu 占用过高) }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论