473,725 Members | 2,070 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 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);
}

Jul 21 '05 #1
0 8369

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

Similar topics

2
1896
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 job did infact complete successfully.(Note: Once the jobs are completed the service simply keeps checking a folder on the network for more files to process, if it doesnt find them it just sits and does nothing. It checks every minute and works...
1
1327
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 button and a Result textbox. I may easily start the asynchronous execution in the Compute_Click event handler. The asynchronous service notifies me when it's result is ready, the notification is done by a delegate invoking ResultReady(...). My...
3
3285
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 start and stop of the service...this works fine. However, I am trying to test the "ticking" of the timer control and have an emailer in the sub that handles the timer tick, unfortunately it does not appear to be ticking... Can anyone tell me...
0
833
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 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...
9
2801
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 Now. This seems that it will create a lot of processor overhead in terms of 'how often shall I check the db?'. I wonder if I check it hourly and save additional info. as a timespan...I just don't know......has anyone got any ideas of best practice...
3
2404
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 CanHandlePowerEvent = true. But the service still fails to reject standby. If I do the same in VS2003, it does reject standby, anyone else done or seen this with VS2005? Even if I set the code to return false to all PowerBroadcastStatus events, it still doesn't...
0
2891
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# Windows service has a simple query that checks if a new entry is made into a table, select * from Cast_Member where isMajor = '1' When I insert a new record into this table with isMajor = 1, then the
2
2767
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 shuts down in under 30 seconds, everything is fine. However if the service takes over 30 seconds to shut down, I get the following error in the System Event Log: "Timeout (30000 milliseconds) waiting for a transaction response from the XYZ...
5
1529
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 service creates the report. My question is if a user cancels or closes the browser before the report is completed, but windows service is still in the process of creating a report how do I notify the service to quit creating a report because...
0
8888
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9401
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9113
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8097
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3221
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.