我想开发一个Windows服务,它将检测按下的按键,否则它会在按下按键时启动。那可能吗?
我创建了一段时间后运行的服务并更新了一些数据库表。
以下是我不时更新数据库所做的代码。
System.Timers.Timer timer1 = new System.Timers.Timer();
private void InitializeComponent()
{
((System.ComponentModel.ISupportInitialize)(timer1)).BeginInit();
timer1.Enabled = true;
((System.ComponentModel.ISupportInitialize)(timer1)).EndInit();
}
protected override void OnStart(string[] args)
{
try
{
WriteLog("test Services Started at : " + System.DateTime.Now);
// Time Elapsed event
timer1.Elapsed += new ElapsedEventHandler(OnElapsedTime);
int intOnElapsedTime = Convert.ToInt32(
System.Configuration.ConfigurationManager
.AppSettings["intOnElapsedTime"]
.ToString());
timer1.Interval = 1000 * 10 * intOnElapsedTime;
timer1.Enabled = true;
}
catch (Exception ex)
{
WriteErrorLog(ex.Message, ex.StackTrace, "OnStart");
}
}
private void OnElapsedTime(object sender, ElapsedEventArgs e)
{
try{ /* update database table */}
catch (Exception exp){ ...}
}
答案 0 :(得分:2)
Windows服务不适用于UI交互。与普通窗口(winforms)相比,它们与内核的交互方式不同。即MessageBox.Show("something")
不会在Windows服务中产生任何内容。
您需要查看Keyboard hooks。
在C#中设计一个键盘钩子。你会在谷歌上找到很多。将它放在Windows Service OnStart中。并部署您的服务。
一些好的C#keyBoard Hooks:
因此,这些将帮助您捕获按下的键。然后您可以轻松检查,按下了什么键并执行操作。你甚至不需要定时器控制。
此外,按下Windows服务中的某个键执行某项任务是一个非常糟糕的主意,因为您可能会一次又一次地按下,一次又一次地运行您的逻辑。
您应该在Windows服务中部署代码。并通过Windows任务计划程序调用它。
This是您安排任务的方式