Như các bạn cũng đã biết rồi đấy, nếu bạn muốn khởi động một chương trình trong khoảng thời gian bạn muốn định sẳn thì chỉ cần dùng chương trình này để cấp quyền khởi động theo thời gian bạn muốn mà không còn phải chờ đợi hay đặt thời gian để nó tự khởi động nữa, và việc khởi động chương trình lên cùng với máy tính thì có nhiều cách nhưng nó không cho bạn khởi động theo thời gian định sẳn.
Ví dụ bạn muốn khởi động cùng windows khi máy tính được mỡ thì chương trình sẽ khởi động cùng windows như unikey hoặc nhiều chương trình khác.
Bạn chỉ cần gỏ tổ hợp phím
WINDOWS+R
và nhập vào khung đó đoạn mã shell:startup
nó sẽ hiện thị ra một thư mục và bạn copy chương trình bạn muốn khởi động cùng windows vào là mỗi khi bạn khởi động máy tính nó sẽ tự động mỡ chương trình đó lên.Bên dưới là hình ảnh chương trình.
Với chương trình, bạn có thể thêm, chỉnh sửa hoặc xóa ứng dụng.
- Lên lịch đến giờ để chạy ứng dụng.
-
Thông tin ứng dụng được lưu trữ ở
database Sqlite
. - Ứng dụng có tính năng khởi động ứng dụng cùng windows.
- Hiển thị thông tin nhật ký chạy ứng dụng.
- App được viết trên nền NetCore
FULL SOURCE CODE
using BrightIdeasSoftware; using Microsoft.Win32; using MySchedulerApp.Helpers; using System; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Management; using System.Windows.Forms; namespace MySchedulerApp { public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); } public List<(Process, string)> LIST_PROCESS = new List<(Process, string)>(); public void updateStatus(int isrunning) { SQLHelper.Instance.ExecQueryNonData($"update tbl_scheduler set running={isrunning}"); } public void StartMonitoring() { Thread monitoringThread = new Thread(() => { while (true) { foreach (var (process, filename) in LIST_PROCESS.ToList()) { if (process.HasExited) { Console.WriteLine($"Process for {filename} has been killed."); SQLHelper.Instance.ExecQueryNonData($"update tbl_scheduler set running=0 where name=@name", new { name = filename }); LIST_PROCESS.Remove((process, filename)); LoadScheduler(); } } Thread.Sleep(1000); } }); monitoringThread.Start(); } protected override void OnShown(EventArgs e) { base.OnShown(e); var isStartup = Convert.ToInt16(SQLHelper.Instance.ExecQuerySacalar("select startup from tbl_startup where id=1").ToString()) > 0; chkAutoStart.Checked = isStartup; var isBatHopThoai = Convert.ToInt16(SQLHelper.Instance.ExecQuerySacalar("select startup from tbl_startup where id=2").ToString()) > 0; chkBatHopThoai.Checked = isBatHopThoai; StartMonitoring(); if (!isBatHopThoai) { this.Hide(); } } public void LoadScheduler() { var data = SQLHelper.Instance.ExecQueryData<SchedulerItem>("select * from tbl_scheduler").ToList(); olvData.SetObjects(data); } private void btnSave_Click(object sender, EventArgs e) { var name = txtPath.Text.Trim(); var starttime = txtTime.Text.Trim(); if (string.IsNullOrEmpty(name)) { MessageBox.Show("Bạn chưa chọn đường dẫn ứng dụng *.exe, *.jar.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (string.IsNullOrEmpty(starttime)) { MessageBox.Show("Bạn chưa chọn thời gian.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!File.Exists(name)) { MessageBox.Show($"Đường dẫn file: {name} không tồn tại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // kiểm tra xem ứng dụng và thời gian có trùng nhau không var isExist = Convert.ToInt32(SQLHelper.Instance.ExecQuerySacalar("select count(*) from tbl_scheduler where name=@name and starttime=@starttime", new { name, starttime })) > 0; if (isExist) { MessageBox.Show($"Thời gian: {starttime}, cài đặt cho ứng dụng: {name} đã tồn tại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } SQLHelper.Instance.ExecQueryNonData("insert into tbl_scheduler(name, starttime) select @name, @starttime", new { name, starttime }); LoadScheduler(); } private void btnBrowserApp_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = "Chọn ứng dụng"; openFileDialog.InitialDirectory = @"C:\"; openFileDialog.Filter = "Exe or Jar File|*.exe;*.jar"; openFileDialog.Multiselect = false; DialogResult result = openFileDialog.ShowDialog(); if (result == DialogResult.OK) { string selectedFilePath = openFileDialog.FileName; txtPath.Text = selectedFilePath; } } public static bool IsJarFileRunning(string jarFileName) { try { string queryString = $"SELECT CommandLine, ProcessId FROM Win32_Process WHERE Name LIKE '%java%'"; using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(queryString)) { foreach (ManagementObject process in searcher.Get()) { string commandLine = process["CommandLine"] as string; int processId = Convert.ToInt32(process["ProcessId"]); if (commandLine != null && commandLine.Contains(jarFileName)) { Console.WriteLine($"Process ID: {processId}, Command Line: {commandLine}"); return true; } } } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } return false; } private void FrmMain_Load(object sender, EventArgs e) { updateStatus(0); InitCreateObjectListView(); btnStart.PerformClick(); timer.Tick += TimeTick; } private void InitCreateObjectListView() { olvData.OwnerDraw = true; olvData.RowHeight = 35; olvData.HeaderMinimumHeight = 35; olvData.SmallImageList = imageList1; olvData.ShowImagesOnSubItems = true; olvData.BorderStyle = BorderStyle.None; olvData.FormatRow += OlvData_FormatRow; //olvData.CellPadding = new Rectangle(4, 2, 4, 2); //olvData.AllColumns.Add(new OLVColumn() //{ // IsVisible = false, // Text = "ID", // Width = 50, // AspectName = "id", // TextAlign = HorizontalAlignment.Center, // HeaderTextAlign = HorizontalAlignment.Center, //}); var colTrangThai = new OLVColumn() { Text = "Trạng thái", Width = 130, TextAlign = HorizontalAlignment.Center, HeaderTextAlign = HorizontalAlignment.Center, AspectName = "runningtext", IsButton = false, ButtonSizing = OLVColumn.ButtonSizingMode.FixedBounds, ImageGetter = (object rowObject) => { if (rowObject is SchedulerItem row) { if (row.isRunning) { return imageList2.Images[2]; } else { return imageList2.Images[0]; } } return null; } }; olvData.AllColumns.Add(colTrangThai); var colName = new OLVColumn() { Text = "Tên ứng dụng", Width = 240, AspectName = "filename", TextAlign = HorizontalAlignment.Center, HeaderTextAlign = HorizontalAlignment.Center, }; olvData.AllColumns.Add(colName); olvData.AllColumns.Add(new OLVColumn() { Text = "Thời gian", Width = 100, AspectName = "starttime", TextAlign = HorizontalAlignment.Center, HeaderTextAlign = HorizontalAlignment.Center, }); var colEdit = new OLVColumn() { Text = "Sửa", Width = 100, AspectName = "", TextAlign = HorizontalAlignment.Center, HeaderTextAlign = HorizontalAlignment.Center, ImageAspectName = "sua", ImageGetter = obj => { return imageList1.Images[1]; }, IsButton = false, }; olvData.AllColumns.Add(colEdit); olvData.AllColumns.Add(new OLVColumn() { Text = "Xóa", Width = 100, AspectName = "", TextAlign = HorizontalAlignment.Center, HeaderTextAlign = HorizontalAlignment.Center, IsButton = false, ImageGetter = obj => { return imageList1.Images[0]; }, }); olvData.RebuildColumns(); foreach (OLVColumn item in olvData.Columns) { var headerstyle = new HeaderFormatStyle(); headerstyle.SetBackColor(ColorTranslator.FromHtml("#2B3C4D")); headerstyle.SetForeColor(Color.White); headerstyle.SetFont(new Font("Tahoma", 9, FontStyle.Bold)); item.HeaderFormatStyle = headerstyle; } olvData.CellClick += (ss, ee) => { if (ee.ColumnIndex == 3) { var clickedObject = ee.Model as SchedulerItem; if (timer.Enabled) { MessageBox.Show("Bấm nút dừng lại, rồi chỉnh sửa bạn ơi.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var id = clickedObject.id; var data = SQLHelper.Instance.ExecQueryDataAsDataTable("select * from tbl_scheduler where id=@id", new { id }); var frm = new FrmEdit(data); frm.ShowDialog(this); LoadScheduler(); } if (ee.ColumnIndex == 4) { if (timer.Enabled) { MessageBox.Show("Bấm nút dừng lại, rồi xóa bạn ơi.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var dlg = MessageBox.Show("Bạn muốn xóa dòng này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dlg == DialogResult.Yes) { var clickedObject = ee.Model as SchedulerItem; var id = clickedObject.id; SQLHelper.Instance.ExecQueryNonData("delete from tbl_scheduler where id=@id", new { id }); LoadScheduler(); } } if (ee.ColumnIndex == 0) { var clickedObject = ee.Model as SchedulerItem; var filePath = clickedObject.name; if (System.IO.File.Exists(filePath)) { try { // kiểm tra xem ứng dụng đang chạy hay dừng var isRunning = Convert.ToInt16(SQLHelper.Instance.ExecQuerySacalar($"select count(*) from tbl_scheduler where running=1 and name=@name", new { name = filePath })) > 0; if (isRunning) { CloseApplicationByName(filePath); LoadScheduler(); } else { var process = RunProcess(filePath, 1); if (process != null) { LIST_PROCESS.Add((process, filePath)); } } LoadScheduler(); } catch (Exception ex) { WriteLogRun("Error opening the file: " + ex.Message); } } else { WriteLogRun("The selected file does not exist."); } } }; olvData.ButtonClick += (ss, ee) => { if (ee.ColumnIndex == 0) { var clickedObject = ee.Model as SchedulerItem; var filePath = clickedObject.name; if (System.IO.File.Exists(filePath)) { try { // kiểm tra xem ứng dụng đang chạy hay dừng var isRunning = Convert.ToInt16(SQLHelper.Instance.ExecQuerySacalar($"select count(*) from tbl_scheduler where running=1 and name=@name", new { name = filePath })) > 0; if (isRunning) { CloseApplicationByName(filePath); LoadScheduler(); } else { var process = RunProcess(filePath, 1); if (process != null) { LIST_PROCESS.Add((process, filePath)); } } LoadScheduler(); } catch (Exception ex) { WriteLogRun("Error opening the file: " + ex.Message); } } else { WriteLogRun("The selected file does not exist."); } } }; LoadScheduler(); } private void OlvData_FormatRow(object? sender, FormatRowEventArgs e) { if (e.Model != null) { var model = (SchedulerItem)e.Model; if (model.isRunning) { e.Item.BackColor = ColorTranslator.FromHtml("#d9f7be"); } else { e.Item.BackColor = olvData.BackColor; } } } private void ButtonRenderer(EventArgs e, BrightIdeasSoftware.RenderDelegate info) { } private void CloseApplicationByName(string filePath) { foreach (var item in LIST_PROCESS) { if (item.Item2 == filePath) { KillProcessAndChildrens(item.Item1.Id); SQLHelper.Instance.ExecQueryNonData($"update tbl_scheduler set running=0 where name=@name", new { name = filePath }); } } } private void btnStart_Click(object sender, EventArgs e) { dataScheduler = SQLHelper.Instance.ExecQueryData<SchedulerItem>("select * from tbl_scheduler").ToList(); if (dataScheduler.Count > 0) { timer.Start(); btnStop.Enabled = true; btnStart.Enabled = false; // LIST_PROCESS = new List<Process>(); } else { MessageBox.Show("Chưa có lịch thực thi ứng dụng, bạn ơi.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); } } List<SchedulerItem> dataScheduler = new List<SchedulerItem>(); private void TimeTick(object ss, EventArgs ee) { var currentTime = DateTime.Now; var now = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, currentTime.Hour, currentTime.Minute, currentTime.Second); var hasRun = dataScheduler.Any(x => x.start_datetime == now); if (hasRun) { var tasksToRun = dataScheduler.Where(x => x.start_datetime == now).ToList(); foreach (var item in tasksToRun) { //Process.Start(item.name); var process = RunProcess(item.name); if (process != null) { LIST_PROCESS.Add((process, item.name)); } LoadScheduler(); } } } public Process? RunProcess(string filePath, int isManual = 0) { if (Path.GetExtension(filePath).Equals(".jar", StringComparison.OrdinalIgnoreCase)) { var filenameJar = Path.GetFileName(filePath); var isRunning = IsJarFileRunning(filenameJar); if (isRunning) { // MessageBox.Show($"{filenameJar} is running..."); if (isManual == 0) { WriteLogRun($"Ứng dụng {Path.GetFileName(filePath)} đang chạy!"); } else { MessageBox.Show($"Ứng dụng {Path.GetFileName(filePath)} đang chạy!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return null; } string command = $"java -jar \"{filePath}\""; SQLHelper.Instance.ExecQueryNonData($"update tbl_scheduler set running=1 where name=@name", new { name = filePath }); Process p = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "cmd.exe"; startInfo.Arguments = @"/c " + command; // cmd.exe spesific implementation p.StartInfo = startInfo; p.Start(); return p; } else { var filenameExe = Path.GetFileName(filePath); var isRunning = IsProcessRunning(filePath); if (isRunning) { if (isManual == 0) { WriteLogRun($"Ứng dụng {Path.GetFileName(filePath)} đang chạy!"); } else { MessageBox.Show($"Ứng dụng {Path.GetFileName(filePath)} đang chạy!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return null; } var process = Process.Start(filePath); SQLHelper.Instance.ExecQueryNonData($"update tbl_scheduler set running=1 where name=@name", new { name = filePath }); WriteLogRun($"Chạy ứng dụng: {Path.GetFileName(filePath)} ... Done"); return process; } } public static bool IsProcessRunning(string filePath) { string FilePath = Path.GetDirectoryName(filePath); string FileName = Path.GetFileNameWithoutExtension(filePath).ToLower(); bool isRunning = false; Process[] pList = Process.GetProcessesByName(FileName); foreach (Process p in pList) { if (p.MainModule.FileName.Contains(Path.GetFileName(filePath), StringComparison.InvariantCultureIgnoreCase)) { isRunning = true; break; } } return isRunning; } public void WriteLogRun(string message) { rtbLog.AppendText($"[{DateTime.Now.ToString("HH:mm")}]: {message} \n"); rtbLog.ScrollToCaret(); } private void btnStop_Click(object sender, EventArgs e) { timer.Stop(); btnStop.Enabled = false; btnStart.Enabled = true; // ClostAllProcess(); } public void ClostAllProcess() { foreach (var item in LIST_PROCESS) { KillProcessAndChildrens(item.Item1.Id); } LIST_PROCESS.Clear(); } private void KillProcessAndChildrens(int pid) { ManagementObjectSearcher processSearcher = new ManagementObjectSearcher ("Select * From Win32_Process Where ParentProcessID=" + pid); ManagementObjectCollection processCollection = processSearcher.Get(); try { Process proc = Process.GetProcessById(pid); if (!proc.HasExited) proc.Kill(); } catch (ArgumentException) { // Process already exited. } if (processCollection != null) { foreach (ManagementObject mo in processCollection) { KillProcessAndChildrens(Convert.ToInt32(mo["ProcessID"])); //kill child processes(also kills childrens of childrens etc.) } } } private void timer1_Tick(object sender, EventArgs e) { this.Text = $"My Scheduler Application - {DateTime.Now.ToString("HH:mm:ss")}"; } private void btnExit_Click(object sender, EventArgs e) { Application.Exit(); } protected override void OnClosing(CancelEventArgs e) { this.Hide(); notifyIcon1.ShowBalloonTip(800); e.Cancel = true; base.OnClosing(e); } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; } #region "Startup App With Windows Login" string nameApp = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; private bool IsStartupItem() { // The path to the key where Windows looks for startup applications RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); if (rkApp.GetValue(nameApp) == null) // The value doesn't exist, the application is not set to run at startup return false; else // The value exists, the application is set to run at startup return true; } private void AddStartupApplication() { RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); if (!IsStartupItem()) { rkApp.SetValue(nameApp, Application.ExecutablePath.ToString()); MessageBox.Show("Đã kích hoạt phần mềm tự khởi động cùng window thành công!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void RemoveStartupApplication() { RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); if (IsStartupItem()) { rkApp.DeleteValue(nameApp, false); MessageBox.Show("Đã tắt chức năng phần mềm tự khởi động cùng window thành công!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information); } } #endregion private void chkAutoStart_CheckedChanged(object sender, EventArgs e) { if (chkAutoStart.Checked) { AddStartupApplication(); SQLHelper.Instance.ExecQueryNonData("update tbl_startup set startup=1 where id=1"); } else { RemoveStartupApplication(); SQLHelper.Instance.ExecQueryNonData("update tbl_startup set startup=0 where id=1"); } } private void chkBatHopThoai_CheckedChanged(object sender, EventArgs e) { if (chkBatHopThoai.Checked) { SQLHelper.Instance.ExecQueryNonData("update tbl_startup set startup=1 where id=2"); } else { SQLHelper.Instance.ExecQueryNonData("update tbl_startup set startup=0 where id=2"); } } private void btnThoat_Click(object sender, EventArgs e) { Application.Exit(); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("https://hung.pro.vn"); } } }
Qua đoạn code bên trên mọi người cùng biết cần thêm bớt gì ở chương trình để phù hợp với khả năng và công dụng bạn muốn.
Chúc mọi người thành công với chương trình trên.
Theo LapTrinhVB.Net
Comments