469,623 Members | 1,422 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,623 developers. It's quick & easy.

USB Service Notification in c# using handler

I am writing a windows service that will recieve
notification when a USB Device is insterted into the
machine. I have used the RegisterDeviceNotification and
the RegisterServiceCtrlHandlerEx 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.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Runtime.InteropServices;

namespace WindowsServiceTest1
{
public delegate void callbackEx(int control,int
eventType,IntPtr
eventData,IntPtr context);

public class MyNewService :
System.ServiceProcess.ServiceBase
{
private System.Diagnostics.EventLog
eventLog1;
private System.Diagnostics.Process
process1;
private System.Diagnostics.Process p;
System.Threading.Thread t2;
callbackEx myCallback;
private IntPtr handleMethod ;
MyForm my;

//System.Threading.Thread errorthread1=new
System.Threading.Thread(new System.Threading.ThreadStart
(showErrorMessage));
System.Threading.Thread tnotification;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container
components = null;

public MyNewService()
{

InitializeComponent();

}

// The main entry point for the process
static void Main()
{
System.ServiceProcess.ServiceBase
[] ServicesToRun;
ServicesToRun = new
System.ServiceProcess.ServiceBase[] { new MyNewService() };

System.ServiceProcess.ServiceBase.Run
(ServicesToRun);
}

/// <summary>
///
/// </summary>
private static void showErrorMessage()
{

System.Windows.Forms.MessageBox.Show("MyForm
Message RegisterServiceCtrlHandlerEx error:" +
Win32.GetLastError().ToString
(),"ss",System.Windows.Forms.MessageBoxButtons.OK, System.Wi
ndows.Forms.MessageBoxIcon.Information,System.Wind ows.Forms
..MessageBoxDefaultButton.Button3,System.Windows.F orms.Messa
geBoxOptions.ServiceNotification);
}
/// <summary>
/// Required method for Designer support -
do not modify
/// the contents of this method with the
code editor.
/// </summary>
private void InitializeComponent()
{
string
notificationMessage="RegisterServiceCtrlHandler {0} error
number {1}";

//tnotification=new System.Threading.Thread
(new System.Threading.ThreadStart
(RegisterHidNotification));
myCallback = new callbackEx
(this.callbackexfunc);
handleMethod
=RegisterServiceCtrlHandlerEx
(this.ServiceName,myCallback,IntPtr.Zero );

System.Windows.Forms.MessageBox.Show(string.Format
(notificationMessage,handleMethod.ToString(),
Win32.GetLastError().ToString
()),"ss",System.Windows.Forms.MessageBoxButtons.OK ,System.W
indows.Forms.MessageBoxIcon.Information,System.Win dows.Form
s.MessageBoxDefaultButton.Button3,System.Windows.F orms.Mess
ageBoxOptions.ServiceNotification);

#region oldstuff

this.eventLog1 = new
System.Diagnostics.EventLog();
this.process1 = new
System.Diagnostics.Process();

((System.ComponentModel.ISupportInitialize)
(this.eventLog1)).BeginInit();
//
// eventLog1
//
this.eventLog1.Log = "MyNewLog";
this.eventLog1.Source = "Godfrey";
//
// MyNewService
//
this.CanHandlePowerEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.ServiceName = "ServiceTest";

((System.ComponentModel.ISupportInitialize)
(this.eventLog1)).EndInit();

// my=new MyForm();
// my.DeviceChangeEvent+=new
DeviceChange(my_DeviceChangeEvent);

#endregion

}

/// <summary>
/// Clean up any resources being used.
/// </summary>
///
protected override void Dispose( bool
disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose
();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Set things in motion so your service
can do its work.
/// </summary>
protected override void OnStart(string[]
args)
{
if(!EventLog.SourceExists
("Godfrey"))
{
EventLog.CreateEventSource
("Godfrey", "GodfreySource");
}

eventLog1.Source = "Godfrey";
eventLog1.WriteEntry("In OnStart");
//RegisterHidNotification
//tnotification.Start();

RegisterHidNotification();
eventLog1.WriteEntry("Done
started");

}
public void RegisterHidNotification()
{

Win32.DEV_BROADCAST_DEVICEINTERFACE dbi = new

Win32.DEV_BROADCAST_DEVICEINTERFACE();
int size = Marshal.SizeOf(dbi);
dbi.dbcc_size = size;
dbi.dbcc_devicetype =
Win32.DBT_DEVTYP_DEVICEINTERFACE;
dbi.dbcc_reserved = 0;
dbi.dbcc_classguid =
Win32.GUID_DEVINTERFACE_HID;
dbi.dbcc_name = 0;
IntPtr buffer =
Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(dbi,
buffer, true);

IntPtr r =
Win32.RegisterDeviceNotification(handleMethod, buffer,

Win32.DEVICE_NOTIFY_SERVICE_HANDLE);
if(r == IntPtr.Zero)

System.Windows.Forms.MessageBox.Show("MyForm
Message error:" + Win32.GetLastError().ToString
(),"ss",System.Windows.Forms.MessageBoxButtons.OK, System.Wi
ndows.Forms.MessageBoxIcon.Information,System.Wind ows.Forms
..MessageBoxDefaultButton.Button3,System.Windows.F orms.Messa
geBoxOptions.ServiceNotification);

}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{

//System.Diagnostics.EventLog.CreateEventSource
("MyApp1aa", "MyNewLog");

if(!EventLog.SourceExists
("Godfrey"))
{
EventLog.CreateEventSource
("Godfrey", "GodfreySource");
}

eventLog1.Source = "Godfrey";
eventLog1.WriteEntry("In OnStop");
// TODO: Add code here to perform
any tear-down necessary to stop your service.
}
protected override void OnContinue()
{
if(!EventLog.SourceExists
("Godfrey"))
{
EventLog.CreateEventSource
("Godfrey", "GodfreySource");
}

/eventLog1.Source = "Godfrey";
eventLog1.WriteEntry("In
OnContinue.");
}

#region pinvoke stuff

[DllImport("advapi32.dll",
SetLastError=true)]
static extern IntPtr
RegisterServiceCtrlHandlerEx(string
lpServiceName,callbackEx
cbex,IntPtr context);
public void callbackexfunc(int
control,int eventType,IntPtr
eventData,IntPtr context)
{

System.Windows.Forms.MessageBox.Show("callback
worked:" + eventData.ToString
(),"ss",System.Windows.Forms.MessageBoxButtons.OK, System.Wi
ndows.Forms.MessageBoxIcon.Information,System.Wind ows.Forms
..MessageBoxDefaultButton.Button3,System.Windows.F orms.Messa
geBoxOptions.ServiceNotification);

}

#endregion

#region oldstuff

private void MessageBox()
{

System.Windows.Forms.MessageBox.Show("I am
here","DDD",System.Windows.Forms.MessageBoxButtons .OK,Syste
m.Windows.Forms.MessageBoxIcon.Information,System. Windows.F
orms.MessageBoxDefaultButton.Button3,

System.Windows.Forms.MessageBoxOptions.ServiceNoti f
ication);
}
protected System.IntPtr mytest()
{
return new System.IntPtr(111111);
}
protected void my_DeviceChangeEvent
(System.Windows.Forms.Message m)
{

System.Windows.Forms.MessageBox.Show("Event
notification:" + m.ToString(),"Service Event
Notification",System.Windows.Forms.MessageBoxButto ns.OK,Sys
tem.Windows.Forms.MessageBoxIcon.Information,Syste m.Windows
..Forms.MessageBoxDefaultButton.Button3,

System.Windows.Forms.MessageBoxOptions.ServiceNoti f
ication);
}
private void ShowForm()
{
TestForm x= new TestForm();
x.Show();
}
private void ShowMyForm()
{
my.blah();
}

private void StartListening()
{
my.RegisterHidNotification();
}
/// <summary>
/// Set things in motion so your service
can do its work.
/// </summary>
protected void OldOnStart(string[] args)
{
if(!EventLog.SourceExists
("Godfrey"))
{
EventLog.CreateEventSource
("Godfrey", "GodfreySource");
}

eventLog1.Source = "Godfrey";
eventLog1.WriteEntry("In OnStart");

//
eventLog1.WriteEntry("In OnStart Before form
launch");
//
System.Threading.Thread tf=new
System.Threading.Thread(new System.Threading.ThreadStart
(ShowForm));
// tf.Start();

t2=new System.Threading.Thread(new
System.Threading.ThreadStart( StartListening));
t2.Start();

eventLog1.WriteEntry("In OnStart
after form launch");

//
eventLog1.WriteEntry("In OnStart Launching
explorer");
//
OpenWithArguments();
//
SomeOtherStartProcess();
//
System.Threading.Thread t=new
System.Threading.Thread(new System.Threading.ThreadStart(
this.MessageBox));
// t.Start();

my.enableEvents=true;
eventLog1.WriteEntry("Done
started");

}
/// <summary>
/// Opens urls and .html documents using
Internet Explorer.
/// </summary>
public void OpenWithArguments()
{
// url's are not considered
documents. They can only be opened
// by passing them as arguments.
//Process.Start
("IExplore.exe", "www.northwindtraders.com");
// Process.Start("notepad.exe");

Process myProcess = new Process();
myProcess.StartInfo.FileName
= "IExplore.exe";

myProcess.StartInfo.Arguments="www.yahoo.com";
myProcess.Start();

Process myProcess2 = new Process();
myProcess2.StartInfo.FileName
= "notepad.exe";
myProcess2.Start();
}

private void SomeOtherStartProcess()
{

System.Diagnostics.ProcessStartInfo psi = new
System.Diagnostics.ProcessStartInfo();
psi.FileName = "NotePad.exe";
psi.WorkingDirectory = @"C:\WINNT";
psi.WindowStyle =
System.Diagnostics.ProcessWindowStyle.Normal;
process1 =
System.Diagnostics.Process.Start(psi);

}

#endregion
}

}

class Win32
{
public const int
SERVICE_CONTROL_DEVICEEVENT=030303;
public const int
WM_DEVICECHANGE = 0x0219;
public const int
DBT_DEVICEARRIVAL = 0x8000,
DBT_DEVICEREMOVECOMPLETE = 0x8004;
public const int
DEVICE_NOTIFY_WINDOW_HANDLE = 0,
DEVICE_NOTIFY_SERVICE_HANDLE = 1;
public const int
DBT_DEVTYP_DEVICEINTERFACE = 5;
// public static Guid
//
GUID_DEVINTERFACE_HID = new
// Guid("4D1E55B2-
F16F-11CF-88CB-001111000030");

//all usb devices
public static Guid
GUID_DEVINTERFACE_HID = new
Guid("A5DCBF10-6530-11D2-901F-
00C04FB951ED");

[StructLayout(LayoutKind.Sequential)]
public class
DEV_BROADCAST_DEVICEINTERFACE
{
public int dbcc_size;
public int dbcc_devicetype;
public int dbcc_reserved;
public Guid dbcc_classguid;
public short dbcc_name;
}

[DllImport("user32.dll",
SetLastError=true)]
public static extern IntPtr
RegisterDeviceNotification(
IntPtr hRecipient,
IntPtr NotificationFilter,
Int32 Flags);

[DllImport("kernel32.dll")]
public static extern int GetLastError();

/// <summary>
/// User to to unregister for listening
mode
/// </summary>
/// <returns></returns>
[DllImport("user32.dll",SetLastError=true)]
public static extern IntPtr
UnregisterDeviceNotification (
IntPtr Handle);
}

Jul 21 '05 #1
0 7927

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Blaz | last post: by
3 posts views Thread by Chris Hayes | last post: by
9 posts views Thread by Phil G. | last post: by
5 posts views Thread by Peter | last post: by
reply views Thread by devrayhaan | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.