AlarmTimer






2.93/5 (9投票s)
这是一个集调度器、邮件发送器和命令行执行器于一体的程序。
引言
该应用程序充当闹钟、提醒、邮件发送器和命令行执行器,所有功能都集成在一个程序中。您可以设置计时器,在指定时间后启动闹钟。您还可以添加一条消息,以便在当时弹出,提醒您需要做的事情。或者,您可以从命令行提示符执行任何命令,或者更好的是,您可以编写一封将在预定时间发送的邮件。现在,如果您只想发送邮件或在不使用计时器的情况下执行命令,这也是可能的。
背景
最初它只是一个简单的调度器,然后当我遇到其他人关于以下问题时,我开始添加这些额外功能:
- 在 C# 中播放声音
- 随邮件发送附件
- 在执行模式下隐藏应用程序
- 获取命令行提示符
使用代码
首先,我们从与计时器相关的代码开始:该应用程序的实现使用了 Andrew Boisen 在文章 使用计时器创建一个简单的闹钟应用程序 中提供的计时器闹钟代码。向 Andrew Boisen 致敬。您可以参考该文章获取详细注释和 Andrew Boisen 使用的全部代码。额外的输入是通过使用 Kernel32.dll
来实现声音的。您需要使用 System.Runtime.InteropServices
命名空间。
//For Sound
using System.Runtime.InteropServices;
将此添加到您的变量声明中。//For Sound
[DllImport("Kernel32.dll")]
public static extern bool Beep(int freq, int duration);
现在,为了发出声音,我们需要Beep(1000,500);
要发送邮件,您需要向您的项目添加对 System.Web
的引用。然后,我们需要添加 System.Web
和 System.Web.Mail
命名空间。//For Mail
using System.Web;
using System.Web.Mail;
下面显示的示例代码自成文档。您也可以将此代码放在您的按钮单击事件中。// Construct a new mail message and fill it
// with information from the form
MailMessage msgMail = new MailMessage();
msgMail.From = txtFrom.Text; //From Textbox
msgMail.To = txtTo.Text; //To Textbox
msgMail.Cc = txtCC.Text; //CC Textbox
msgMail.Bcc = txtBCC.Text; //BCC Textbox
msgMail.Subject = txtSubject.Text; //Subject Textbox
msgMail.Body = txtMessage.Text; //Message Textbox
// if an attachment file is indicated, create it and add it to the message
if (txtAttachment.Text.Length > 0)
msgMail.Attachments.Add(new MailAttachment(
txtAttachment.Text, MailEncoding.Base64));
// Now send the message
SmtpMail.Send(msgMail);
// Indicate that the message has been sent
string strSentMail="";
strSentMail = "Message Sent to " + txtTo.Text;
if(txtCC.Text!="")
strSentMail+= " Carbon Copy Sent to " + txtCC.Text;
if(txtBCC.Text!="")
strSentMail+= " Blind Carbon Copy Sent to " + txtBCC.Text;
MessageBox.Show(strSentMail);
要获取命令行提示符以执行您的命令并退出,请使用下面的代码片段。但首先,我们需要使用 System.Diagnostics
命名空间。//For Command Line
using System.Diagnostics;
然后,您可以添加此代码片段以获取您的命令行提示符。//Declare and instantiate a new process component.
System.Diagnostics.Process process1;
process1= new System.Diagnostics.Process();
//Do not receive an event when the process exits.
process1.EnableRaisingEvents = false;
//The "/C" Tells Windows to Run The Command then Terminate
string strCmdLine;
strCmdLine = "/C " + txtCmd.Text.Trim();
//txtCmd is the text box where we enter the commands
System.Diagnostics.Process.Start("CMD.exe",strCmdLine);
process1.Close();
关注点
我做的唯一有点疯狂的事情是将邮件程序和命令行执行器添加到计时器中。因此,当预定时间结束时,您可以发送邮件并执行命令。您可以根据文本框中输入的实例数量执行任意次数的命令。(这些选项也可以独立于计时器工作。)
结论
让一个简单的应用程序变得真正“不简单”是如此容易。最后,我想用这句话结束 - “如果困惑是知识的第一步,那我一定是天才了。”