Reputation: 1674
I want to develop a windows service which will detect the pressed key or it will start when a key is pressed. is that possible?
I have created a service which runs after a period of time and update some database table.
Here is the code what I have done to update database after time to time.
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){ ...}
}
Upvotes: 1
Views: 7483
Reputation: 12375
Windows Service are not meant for UI Interaction. They interact differently with kernel in comparison to normal windows (winforms). i.e. MessageBox.Show("something")
won't produce anything inside a Windows Service.
you need to look into Keyboard hooks.
design a keyboard hook in C#. you will find plenty on the google. place it inside the Windows Service OnStart. and deploy your Service.
Some good C# keyBoard Hooks:
So these will help you to trap the key pressed. And then you can easily check, what key is pressed and perform your action. You don't even need the timer control.
Besides, it is a very bad idea to perform some task upon press of a key inside a windows service, because you might run your logic again and again, by accidently pressing again and again.
What you should do is, to deploy your code in a windows Service. and Invoke it through Windows Task Scheduler.
This is how you can schedule a Task
Upvotes: 3