473,320 Members | 2,094 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,320 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 8304

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: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.