473,385 Members | 1,707 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,385 software developers and data experts.

Global hooks (experts)

Hello,

I'm doing a Taskbar like app and I need to show open application's buttons.
I've chosen to use a global hook due to elevate resource comsumptions by
using a timer that looks up running processes. I'm trying with the
SetWindowEventHook API and it works fine until I open four or five windows.
Below, I show source code and exception stack trace. I'm grateful with any
solution or idea.

In class constructor:

....
IniciaHook();
....

Hook initialization:

private void IniciaHook()
{
API.Win32.SetWinEventHook((int)API.Win32.HookEvent Constants.EVENT_OBJECT_CREATE,
(int)API.Win32.HookEventConstants.EVENT_OBJECT_CRE ATE, 0, new
API.Win32.WinEventProc(WinEventProcedure), 0,0,
(int)API.Win32.HookFlags.WINEVENT_OUTOFCONTEXT);
}

Delegate linked function:

private int WinEventProcedure(int hWinEventHook, int idEvent, int hwnd, int
idObject, int idChild, int dwEventThread, int dwmsEventTime)
{
int pId;
try
{
int length = API.Win32.GetWindowTextLength((IntPtr) hwnd);
if(length > 0)
{
if(idObject==(int)API.Win32.HookObjId.OBJID_WINDOW )
{
StringBuilder sb = new StringBuilder(length + 1);
API.Win32.GetWindowText((IntPtr) hwnd, sb, sb.Capacity);
if(hwnd!=0)
{
API.Win32.GetWindowThreadProcessId((IntPtr) hwnd, out pId);
if(!arLst.Contains(pId))
{
arLst.Add(pId);
Process p=Process.GetProcessById(pId);
addProcess(p.Id, p.MainWindowTitle, p.MainModule.FileName, p.StartTime);
}
}
}
}
}
catch(Exception exc)
{
MessageBox.Show(exc.Message);
}
return 0;
}

Method which add button to taskBar:
public void addProcess(int idProc, string windowName, string exeName,
DateTime pCreate)
{
try
{
XDesktop.TaskBarButton btn=new TaskBarButton();
btn.Height=panel3.Height-4;
btn.ProcessId=idProc;
btn.WindowName=windowName;
btn.Font=new Font(btn.Font.Name,9);
btn.ForeColor=Color.White;
btn.ContextMenu=cMenuButton;
btn.executableName=exeName;
btn.FechaCreacion=pCreate;
this.InsertButton(btn);
if(panel3.Controls.Count<=10)
{
panel3.Controls.Add(btn);
redimensionaBotones();
}
else
{
etbFrm.AddButton(btn);
}
btnMas.Visible=(btCol.Count > panel3.Controls.Count);
}
catch(Exception exc)
{
MessageBox.Show(exc.Message + "\n" + exc.Source + "\n" + exc.StackTrace);
}
}

API functions definition (enumeration definitions are omitted):
[DllImport("user32.dll", EntryPoint="SetWinEventHook", SetLastError=true,
CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern int SetWinEventHook(int eventMin, int eventMax, int
hmodWinEventProc,
WinEventProc lpfnWinEventProc, int idProcess, int idThread, int dwflags);
public delegate int WinEventProc(int hWinEventHook, int idEvent, int hwnd,
int idObject, int idChild, int dwEventThread, int dwmsEventTime);

[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, out STRINGBUFFER
ClassName, int nMaxCount);
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder
lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("User32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int
processId);

Stacktrace information:
Excepción no controlada: System.NullReferenceException: Referencia a objeto
no establecida como instancia de un objeto.
at API.WinEventProc.Invoke(Int32 hWinEventHook, Int32 idEvent, Int32 hwnd,
Int32 idObject, Int32 idChild, Int32 dwEventThread, Int32 dwmsEventTime)
at System.Windows.Forms.UnsafeNativeMethods.PeekMessa ge(MSG& msg, HandleRef
hwnd, Int32 msgMin, Int32 msgMax, Int32 remove)
at
System.Windows.Forms.ComponentManager.System.Windo ws.Forms.UnsafeNativeMethods+IMsoComponentManager. FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.ThreadContext.RunMessageLoopI nner(Int32 reason,
ApplicationContext context)
at System.Windows.Forms.ThreadContext.RunMessageLoop( Int32 reason,
ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationCo ntext context)
at TaskBar.Inicio.Main() in c:\documents and settings\administrador\mis
documentos\visual studio projects\taskbar\inicio.cs:line 90El programa
'[3148] TaskBar.exe' terminó con código 0 (0x0).

I think, error is in delegate or in the associated function, but I'm not
able to find where the error is. I'm blocked and I can't go on.
Thanks.
Nov 17 '05 #1
2 6422
Can you show the code for API.WinEventProc?

Are you sure WinEventProc isn't null? Are you sure none of the handles
you're passing in are null?

Pete

"Víctor" <vi******@vodafone.es> wrote in message
news:eX**************@TK2MSFTNGP09.phx.gbl...
Hello,

I'm doing a Taskbar like app and I need to show open application's
buttons. I've chosen to use a global hook due to elevate resource
comsumptions by using a timer that looks up running processes. I'm trying
with the SetWindowEventHook API and it works fine until I open four or
five windows. Below, I show source code and exception stack trace. I'm
grateful with any solution or idea.

In class constructor:

...
IniciaHook();
...

Hook initialization:

private void IniciaHook()
{
API.Win32.SetWinEventHook((int)API.Win32.HookEvent Constants.EVENT_OBJECT_CREATE,
(int)API.Win32.HookEventConstants.EVENT_OBJECT_CRE ATE, 0, new
API.Win32.WinEventProc(WinEventProcedure), 0,0,
(int)API.Win32.HookFlags.WINEVENT_OUTOFCONTEXT);
}

Delegate linked function:

private int WinEventProcedure(int hWinEventHook, int idEvent, int hwnd,
int
idObject, int idChild, int dwEventThread, int dwmsEventTime)
{
int pId;
try
{
int length = API.Win32.GetWindowTextLength((IntPtr) hwnd);
if(length > 0)
{
if(idObject==(int)API.Win32.HookObjId.OBJID_WINDOW )
{
StringBuilder sb = new StringBuilder(length + 1);
API.Win32.GetWindowText((IntPtr) hwnd, sb, sb.Capacity);
if(hwnd!=0)
{
API.Win32.GetWindowThreadProcessId((IntPtr) hwnd, out pId);
if(!arLst.Contains(pId))
{
arLst.Add(pId);
Process p=Process.GetProcessById(pId);
addProcess(p.Id, p.MainWindowTitle, p.MainModule.FileName, p.StartTime);
}
}
}
}
}
catch(Exception exc)
{
MessageBox.Show(exc.Message);
}
return 0;
}

Method which add button to taskBar:
public void addProcess(int idProc, string windowName, string exeName,
DateTime pCreate)
{
try
{
XDesktop.TaskBarButton btn=new TaskBarButton();
btn.Height=panel3.Height-4;
btn.ProcessId=idProc;
btn.WindowName=windowName;
btn.Font=new Font(btn.Font.Name,9);
btn.ForeColor=Color.White;
btn.ContextMenu=cMenuButton;
btn.executableName=exeName;
btn.FechaCreacion=pCreate;
this.InsertButton(btn);
if(panel3.Controls.Count<=10)
{
panel3.Controls.Add(btn);
redimensionaBotones();
}
else
{
etbFrm.AddButton(btn);
}
btnMas.Visible=(btCol.Count > panel3.Controls.Count);
}
catch(Exception exc)
{
MessageBox.Show(exc.Message + "\n" + exc.Source + "\n" + exc.StackTrace);
}
}

API functions definition (enumeration definitions are omitted):
[DllImport("user32.dll", EntryPoint="SetWinEventHook", SetLastError=true,
CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern int SetWinEventHook(int eventMin, int eventMax, int
hmodWinEventProc,
WinEventProc lpfnWinEventProc, int idProcess, int idThread, int dwflags);
public delegate int WinEventProc(int hWinEventHook, int idEvent, int hwnd,
int idObject, int idChild, int dwEventThread, int dwmsEventTime);

[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, out STRINGBUFFER
ClassName, int nMaxCount);
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder
lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("User32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int
processId);

Stacktrace information:
Excepción no controlada: System.NullReferenceException: Referencia a
objeto
no establecida como instancia de un objeto.
at API.WinEventProc.Invoke(Int32 hWinEventHook, Int32 idEvent, Int32 hwnd,
Int32 idObject, Int32 idChild, Int32 dwEventThread, Int32 dwmsEventTime)
at System.Windows.Forms.UnsafeNativeMethods.PeekMessa ge(MSG& msg,
HandleRef
hwnd, Int32 msgMin, Int32 msgMax, Int32 remove)
at
System.Windows.Forms.ComponentManager.System.Windo ws.Forms.UnsafeNativeMethods+IMsoComponentManager. FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.ThreadContext.RunMessageLoopI nner(Int32 reason,
ApplicationContext context)
at System.Windows.Forms.ThreadContext.RunMessageLoop( Int32 reason,
ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationCo ntext context)
at TaskBar.Inicio.Main() in c:\documents and settings\administrador\mis
documentos\visual studio projects\taskbar\inicio.cs:line 90El programa
'[3148] TaskBar.exe' terminó con código 0 (0x0).

I think, error is in delegate or in the associated function, but I'm not
able to find where the error is. I'm blocked and I can't go on.
Thanks.

Nov 17 '05 #2
API.Win32.SetWinEventHook((int)API.Win32.HookEven tConstants.EVENT_OBJECT_CREATE,
(int)API.Win32.HookEventConstants.EVENT_OBJECT_CR EATE, 0, new
API.Win32.WinEventProc(WinEventProcedure), 0,0,
(int)API.Win32.HookFlags.WINEVENT_OUTOFCONTEXT) ;


You shouldn't create the callback delegate inline like this. You have
to keep a reference to it as long as the hook in active to prevent it
from being garbage collected.
Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 17 '05 #3

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

Similar topics

3
by: paul francis | last post by:
Hi Please help because I'm really stuck: I'm trying to write an application in C# which can be used to track the mouse pointer position on any window. I'm trying to use a Global mouse hook to...
0
by: John Wood | last post by:
It seems that this chap has proven this claim wrong (at least for mouse and keyboard hooks): http://www.codetools.com/useritems/globalhook.asp
3
by: cichy83 | last post by:
Hi! I have a problem with global hooks under these two OS. I'm using three following types of hooks: CBT Hokk, Keyboard Hook, Mouse Hooks. I'm using BCB 6, under Win XP everything works fine...
2
by: tshad | last post by:
I am setting up Authentication that I want to put in multiple Web Sites on my server. I found a good article on this and am looking at moving my code from my Global.asax file to an HTTP Module. ...
2
by: Lunchtimemama | last post by:
I am trying to modify another application's window (Google Talk) to insert some UI of my own. I think the best method would be to install a remote local hook in gtalk's thread that intercepts the...
0
by: effone | last post by:
I have two addins installed in my Outlook 2003, both have their specific functionality, I would like to integrate the functionality of both thru global mouse hooks, here is my senerio 1) Lets say...
23
by: David Colliver | last post by:
Hi, using c#, 1.1 I know that we are not supposed to use global variables etc. in c# I am having a problem, but not sure how to resolve. I did have another post here, but may have over...
0
by: ramon.talavera | last post by:
Hello, I am trying to read rawinput as I have to distinguish between two devices (mice), I have found several examples and I am able to detect Raw Input in the local window, but cannot...
2
by: yuhongbao_386 | last post by:
Is using Reverse P/Invoke in a .NET DLL for installing global hooks supported?
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...

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.