473,401 Members | 2,125 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,401 software developers and data experts.

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 8317

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Blaz | last post by:
I have a windows service that does some stuff. It runs a couple of batch files. After the successful execution of a batch file I need to display some sort of notification to the end user that the...
1
by: Henrik Dahl | last post by:
Issue: I have a remote service executing notoriously asynchronously which I must be able to use from my Compute_Click(...) event handler. The WebForm I have contains only two controls: A Compute...
3
by: Chris Hayes | last post by:
I'm trying to create a nifty Windows Service that will perform tasks at a predetermined interval. To make sure I understand the timing correctly I have set an emailer utility to email me on the...
0
by: grutta | last post by:
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...
9
by: Phil G. | last post by:
Hi all, I would like to create a very simple 'lite' version of Outlook Calendar's reminder function. I will use a windows service that will read timedate stamps from a db and compare them to...
3
by: dr | last post by:
I created a basic service using VS2005. Add OnPowerEvent method as detailed on MSDN and return false to a PowerBroadcastStatus.QuerySuspend notification. The service also has set...
0
by: das | last post by:
Hello all, I am using the SqlDependency to subscribe to any new inserts into a database table, I enabled the DB to be borker ready and subscrbed to Query notifications on the database. My C#...
2
by: Bill Davidson | last post by:
All: I have a Win32 service that takes about 30 seconds to shutdown (give or take a few seconds). I shut the service down via the 'Services' console on Windows Server 2003. When the service...
5
by: Peter | last post by:
I have a webpage which creates reports, a report can take few seconds or several minutes to create. This webpage calls a web service which in turn does a remoting call to a windows service and the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.