I am writing a windows service that will recieve
notification when a USB Device is insterted into the
machine. I have used the RegisterDeviceN otification and
the RegisterService CtrlHandlerEx with a handler. The
handler portion seems to fail indicating that my
parameters are invalid. I am getting an error code 126
when i try to register the handler and 28 when i register
for event notification. Any ideas as to what the deal is?
I am posting my code below.
using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Diagnost ics;
using System.ServiceP rocess;
using System.Runtime. InteropServices ;
namespace WindowsServiceT est1
{
public delegate void callbackEx(int control,int
eventType,IntPt r
eventData,IntPt r context);
public class MyNewService :
System.ServiceP rocess.ServiceB ase
{
private System.Diagnost ics.EventLog
eventLog1;
private System.Diagnost ics.Process
process1;
private System.Diagnost ics.Process p;
System.Threadin g.Thread t2;
callbackEx myCallback;
private IntPtr handleMethod ;
MyForm my;
//System.Threadin g.Thread errorthread1=ne w
System.Threadin g.Thread(new System.Threadin g.ThreadStart
(showErrorMessa ge));
System.Threadin g.Thread tnotification;
/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r
components = null;
public MyNewService()
{
InitializeCompo nent();
}
// The main entry point for the process
static void Main()
{
System.ServiceP rocess.ServiceB ase
[] ServicesToRun;
ServicesToRun = new
System.ServiceP rocess.ServiceB ase[] { new MyNewService() };
System.ServiceP rocess.ServiceB ase.Run
(ServicesToRun) ;
}
/// <summary>
///
/// </summary>
private static void showErrorMessag e()
{
System.Windows. Forms.MessageBo x.Show("MyForm
Message RegisterService CtrlHandlerEx error:" +
Win32.GetLastEr ror().ToString
(),"ss",System. Windows.Forms.M essageBoxButton s.OK,System.Wi
ndows.Forms.Mes sageBoxIcon.Inf ormation,System .Windows.Forms
..MessageBoxDef aultButton.Butt on3,System.Wind ows.Forms.Messa
geBoxOptions.Se rviceNotificati on);
}
/// <summary>
/// Required method for Designer support -
do not modify
/// the contents of this method with the
code editor.
/// </summary>
private void InitializeCompo nent()
{
string
notificationMes sage="RegisterS erviceCtrlHandl er {0} error
number {1}";
//tnotification=n ew System.Threadin g.Thread
(new System.Threadin g.ThreadStart
(RegisterHidNot ification));
myCallback = new callbackEx
(this.callbacke xfunc);
handleMethod
=RegisterServic eCtrlHandlerEx
(this.ServiceNa me,myCallback,I ntPtr.Zero );
System.Windows. Forms.MessageBo x.Show(string.F ormat
(notificationMe ssage,handleMet hod.ToString(),
Win32.GetLastEr ror().ToString
()),"ss",System .Windows.Forms. MessageBoxButto ns.OK,System.W
indows.Forms.Me ssageBoxIcon.In formation,Syste m.Windows.Form
s.MessageBoxDef aultButton.Butt on3,System.Wind ows.Forms.Mess
ageBoxOptions.S erviceNotificat ion);
#region oldstuff
this.eventLog1 = new
System.Diagnost ics.EventLog();
this.process1 = new
System.Diagnost ics.Process();
((System.Compon entModel.ISuppo rtInitialize)
(this.eventLog1 )).BeginInit();
//
// eventLog1
//
this.eventLog1. Log = "MyNewLog";
this.eventLog1. Source = "Godfrey";
//
// MyNewService
//
this.CanHandleP owerEvent = true;
this.CanPauseAn dContinue = true;
this.CanShutdow n = true;
this.ServiceNam e = "ServiceTes t";
((System.Compon entModel.ISuppo rtInitialize)
(this.eventLog1 )).EndInit();
// my=new MyForm();
// my.DeviceChange Event+=new
DeviceChange(my _DeviceChangeEv ent);
#endregion
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
///
protected override void Dispose( bool
disposing )
{
if( disposing )
{
if (components != null)
{
components.Disp ose
();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Set things in motion so your service
can do its work.
/// </summary>
protected override void OnStart(string[]
args)
{
if(!EventLog.So urceExists
("Godfrey"))
{
EventLog.Create EventSource
("Godfrey", "GodfreySource" );
}
eventLog1.Sourc e = "Godfrey";
eventLog1.Write Entry("In OnStart");
//RegisterHidNoti fication
//tnotification.S tart();
RegisterHidNoti fication();
eventLog1.Write Entry("Done
started");
}
public void RegisterHidNoti fication()
{
Win32.DEV_BROAD CAST_DEVICEINTE RFACE dbi = new
Win32.DEV_BROAD CAST_DEVICEINTE RFACE();
int size = Marshal.SizeOf( dbi);
dbi.dbcc_size = size;
dbi.dbcc_device type =
Win32.DBT_DEVTY P_DEVICEINTERFA CE;
dbi.dbcc_reserv ed = 0;
dbi.dbcc_classg uid =
Win32.GUID_DEVI NTERFACE_HID;
dbi.dbcc_name = 0;
IntPtr buffer =
Marshal.AllocHG lobal(size);
Marshal.Structu reToPtr(dbi,
buffer, true);
IntPtr r =
Win32.RegisterD eviceNotificati on(handleMethod , buffer,
Win32.DEVICE_NO TIFY_SERVICE_HA NDLE);
if(r == IntPtr.Zero)
System.Windows. Forms.MessageBo x.Show("MyForm
Message error:" + Win32.GetLastEr ror().ToString
(),"ss",System. Windows.Forms.M essageBoxButton s.OK,System.Wi
ndows.Forms.Mes sageBoxIcon.Inf ormation,System .Windows.Forms
..MessageBoxDef aultButton.Butt on3,System.Wind ows.Forms.Messa
geBoxOptions.Se rviceNotificati on);
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
//System.Diagnost ics.EventLog.Cr eateEventSource
("MyApp1aa", "MyNewLog") ;
if(!EventLog.So urceExists
("Godfrey"))
{
EventLog.Create EventSource
("Godfrey", "GodfreySource" );
}
eventLog1.Sourc e = "Godfrey";
eventLog1.Write Entry("In OnStop");
// TODO: Add code here to perform
any tear-down necessary to stop your service.
}
protected override void OnContinue()
{
if(!EventLog.So urceExists
("Godfrey"))
{
EventLog.Create EventSource
("Godfrey", "GodfreySource" );
}
/eventLog1.Sourc e = "Godfrey";
eventLog1.Write Entry("In
OnContinue.");
}
#region pinvoke stuff
[DllImport("adva pi32.dll",
SetLastError=tr ue)]
static extern IntPtr
RegisterService CtrlHandlerEx(s tring
lpServiceName,c allbackEx
cbex,IntPtr context);
public void callbackexfunc( int
control,int eventType,IntPt r
eventData,IntPt r context)
{
System.Windows. Forms.MessageBo x.Show("callbac k
worked:" + eventData.ToStr ing
(),"ss",System. Windows.Forms.M essageBoxButton s.OK,System.Wi
ndows.Forms.Mes sageBoxIcon.Inf ormation,System .Windows.Forms
..MessageBoxDef aultButton.Butt on3,System.Wind ows.Forms.Messa
geBoxOptions.Se rviceNotificati on);
}
#endregion
#region oldstuff
private void MessageBox()
{
System.Windows. Forms.MessageBo x.Show("I am
here","DDD",Sys tem.Windows.For ms.MessageBoxBu ttons.OK,Syste
m.Windows.Forms .MessageBoxIcon .Information,Sy stem.Windows.F
orms.MessageBox DefaultButton.B utton3,
System.Windows. Forms.MessageBo xOptions.Servic eNotif
ication);
}
protected System.IntPtr mytest()
{
return new System.IntPtr(1 11111);
}
protected void my_DeviceChange Event
(System.Windows .Forms.Message m)
{
System.Windows. Forms.MessageBo x.Show("Event
notification:" + m.ToString(),"S ervice Event
Notification",S ystem.Windows.F orms.MessageBox Buttons.OK,Sys
tem.Windows.For ms.MessageBoxIc on.Information, System.Windows
..Forms.Message BoxDefaultButto n.Button3,
System.Windows. Forms.MessageBo xOptions.Servic eNotif
ication);
}
private void ShowForm()
{
TestForm x= new TestForm();
x.Show();
}
private void ShowMyForm()
{
my.blah();
}
private void StartListening( )
{
my.RegisterHidN otification();
}
/// <summary>
/// Set things in motion so your service
can do its work.
/// </summary>
protected void OldOnStart(stri ng[] args)
{
if(!EventLog.So urceExists
("Godfrey"))
{
EventLog.Create EventSource
("Godfrey", "GodfreySource" );
}
eventLog1.Sourc e = "Godfrey";
eventLog1.Write Entry("In OnStart");
//
eventLog1.Write Entry("In OnStart Before form
launch");
//
System.Threadin g.Thread tf=new
System.Threadin g.Thread(new System.Threadin g.ThreadStart
(ShowForm));
// tf.Start();
t2=new System.Threadin g.Thread(new
System.Threadin g.ThreadStart( StartListening) );
t2.Start();
eventLog1.Write Entry("In OnStart
after form launch");
//
eventLog1.Write Entry("In OnStart Launching
explorer");
//
OpenWithArgumen ts();
//
SomeOtherStartP rocess();
//
System.Threadin g.Thread t=new
System.Threadin g.Thread(new System.Threadin g.ThreadStart(
this.MessageBox ));
// t.Start();
my.enableEvents =true;
eventLog1.Write Entry("Done
started");
}
/// <summary>
/// Opens urls and .html documents using
Internet Explorer.
/// </summary>
public void OpenWithArgumen ts()
{
// url's are not considered
documents. They can only be opened
// by passing them as arguments.
//Process.Start
("IExplore.exe" , "www.northwindt raders.com");
// Process.Start(" notepad.exe");
Process myProcess = new Process();
myProcess.Start Info.FileName
= "IExplore.e xe";
myProcess.Start Info.Arguments= "www.yahoo.com" ;
myProcess.Start ();
Process myProcess2 = new Process();
myProcess2.Star tInfo.FileName
= "notepad.ex e";
myProcess2.Star t();
}
private void SomeOtherStartP rocess()
{
System.Diagnost ics.ProcessStar tInfo psi = new
System.Diagnost ics.ProcessStar tInfo();
psi.FileName = "NotePad.ex e";
psi.WorkingDire ctory = @"C:\WINNT";
psi.WindowStyle =
System.Diagnost ics.ProcessWind owStyle.Normal;
process1 =
System.Diagnost ics.Process.Sta rt(psi);
}
#endregion
}
}
class Win32
{
public const int
SERVICE_CONTROL _DEVICEEVENT=03 0303;
public const int
WM_DEVICECHANGE = 0x0219;
public const int
DBT_DEVICEARRIV AL = 0x8000,
DBT_DEVICEREMOV ECOMPLETE = 0x8004;
public const int
DEVICE_NOTIFY_W INDOW_HANDLE = 0,
DEVICE_NOTIFY_S ERVICE_HANDLE = 1;
public const int
DBT_DEVTYP_DEVI CEINTERFACE = 5;
// public static Guid
//
GUID_DEVINTERFA CE_HID = new
// Guid("4D1E55B2-
F16F-11CF-88CB-001111000030");
//all usb devices
public static Guid
GUID_DEVINTERFA CE_HID = new
Guid("A5DCBF10-6530-11D2-901F-
00C04FB951ED");
[StructLayout(La youtKind.Sequen tial)]
public class
DEV_BROADCAST_D EVICEINTERFACE
{
public int dbcc_size;
public int dbcc_devicetype ;
public int dbcc_reserved;
public Guid dbcc_classguid;
public short dbcc_name;
}
[DllImport("user 32.dll",
SetLastError=tr ue)]
public static extern IntPtr
RegisterDeviceN otification(
IntPtr hRecipient,
IntPtr NotificationFil ter,
Int32 Flags);
[DllImport("kern el32.dll")]
public static extern int GetLastError();
/// <summary>
/// User to to unregister for listening
mode
/// </summary>
/// <returns></returns>
[DllImport("user 32.dll",SetLast Error=true)]
public static extern IntPtr
UnregisterDevic eNotification (
IntPtr Handle);
}