Attach debugger in C# to another process - c#

I'd like to be able to automatically attach a debugger, something like: System.Diagnostics.Debugger.Launch(), except rather than the current process to another named process. I've got a process name and PID to identify the other process.
Is this possible?

Edit:
GSerjo offered the correct solution. I'd like to share a few thoughts on how to improve it (and an explanation). I hope my improved answer will be useful to to others who experience the same problem.
Attaching the VS Debugger to a Process
Manually
Open the Windows Task Manager (Ctrl + Shift + Esc).
Go to the Tab Processes.
Right click the process.
Select Debug.
Or, within Visual Studio, select Debug > Attach to Process....
Results will vary depending on whether you have access to the source code.
Automatically with C#
A note of caution: The following code is brittle in the sense that certain values,
such as the Visual Studio Version number, are hard-coded. Keep this in mind going forward
if you are planning to distribute your program.
First of all, add a reference to EnvDTE to your project (right click on the references folder in the solution explorer, add reference). In the following code, I'll only show the unusual using directives; the normal ones such as using System are omitted.
Because you are interacting with COM you need to make sure to decorate your Main method (the entry point of your application) with the STAThreadAttribute.
Then, you need to define the IOleMessageFilter Interface that will allow you to interact with the defined COM methods (note the ComImportAttribute). We need to access the message filter so we can retry if the Visual Studio COM component blocks one of our calls.
using System.Runtime.InteropServices;
[ComImport, Guid("00000016-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleMessageFilter
{
[PreserveSig]
int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);
[PreserveSig]
int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);
[PreserveSig]
int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
}
Now, we need to implement this interface in order to handle incoming messages:
public class MessageFilter : IOleMessageFilter
{
private const int Handled = 0, RetryAllowed = 2, Retry = 99, Cancel = -1, WaitAndDispatch = 2;
int IOleMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo)
{
return Handled;
}
int IOleMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
{
return dwRejectType == RetryAllowed ? Retry : Cancel;
}
int IOleMessageFilter.MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
{
return WaitAndDispatch;
}
public static void Register()
{
CoRegisterMessageFilter(new MessageFilter());
}
public static void Revoke()
{
CoRegisterMessageFilter(null);
}
private static void CoRegisterMessageFilter(IOleMessageFilter newFilter)
{
IOleMessageFilter oldFilter;
CoRegisterMessageFilter(newFilter, out oldFilter);
}
[DllImport("Ole32.dll")]
private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter);
}
I defined the return values as constants for better readability and refactored the whole thing a bit to get rid of some of the duplication from the MSDN example, so I hope you'll find it self-explanatory. extern int CoRegisterMessageFilter is our connection to the unmanaged message filter code - you can read up on the extern keyword at MSDN.
Now all that's left is some code illustrating the usage:
using System.Runtime.InteropServices;
using EnvDTE;
[STAThread]
public static void Main()
{
MessageFilter.Register();
var process = GetProcess(7532);
if (process != null)
{
process.Attach();
Console.WriteLine("Attached to {0}", process.Name);
}
MessageFilter.Revoke();
Console.ReadLine();
}
private static Process GetProcess(int processID)
{
var dte = (DTE)Marshal.GetActiveObject("VisualStudio.DTE.10.0");
var processes = dte.Debugger.LocalProcesses.OfType<Process>();
return processes.SingleOrDefault(x => x.ProcessID == processID);
}

Check this out
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using EnvDTE;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
public class ForTest
{
[STAThread]
[Test]
public void Test()
{
var dte = (DTE) Marshal.GetActiveObject("VisualStudio.DTE.10.0");
MessageFilter.Register();
IEnumerable<Process> processes = dte.Debugger.LocalProcesses.OfType<Process>();
var process = processes.SingleOrDefault(x => x.ProcessID == 6152);
if (process != null)
{
process.Attach();
}
}
}
public class MessageFilter : IOleMessageFilter
{
//
// Class containing the IOleMessageFilter
// thread error-handling functions.
// Start the filter.
//
// IOleMessageFilter functions.
// Handle incoming thread requests.
#region IOleMessageFilter Members
int IOleMessageFilter.HandleInComingCall(int dwCallType,
IntPtr hTaskCaller, int dwTickCount, IntPtr
lpInterfaceInfo)
{
//Return the flag SERVERCALL_ISHANDLED.
return 0;
}
// Thread call was rejected, so try again.
int IOleMessageFilter.RetryRejectedCall(IntPtr
hTaskCallee, int dwTickCount, int dwRejectType)
{
if (dwRejectType == 2)
// flag = SERVERCALL_RETRYLATER.
{
// Retry the thread call immediately if return >=0 &
// <100.
return 99;
}
// Too busy; cancel call.
return -1;
}
int IOleMessageFilter.MessagePending(IntPtr hTaskCallee,
int dwTickCount, int dwPendingType)
{
//Return the flag PENDINGMSG_WAITDEFPROCESS.
return 2;
}
#endregion
public static void Register()
{
IOleMessageFilter newFilter = new MessageFilter();
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(newFilter, out oldFilter);
}
// Done with the filter, close it.
public static void Revoke()
{
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(null, out oldFilter);
}
// Implement the IOleMessageFilter interface.
[DllImport("Ole32.dll")]
private static extern int
CoRegisterMessageFilter(IOleMessageFilter newFilter, out
IOleMessageFilter oldFilter);
}
[ComImport, Guid("00000016-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IOleMessageFilter
{
[PreserveSig]
int HandleInComingCall(
int dwCallType,
IntPtr hTaskCaller,
int dwTickCount,
IntPtr lpInterfaceInfo);
[PreserveSig]
int RetryRejectedCall(
IntPtr hTaskCallee,
int dwTickCount,
int dwRejectType);
[PreserveSig]
int MessagePending(
IntPtr hTaskCallee,
int dwTickCount,
int dwPendingType);
}
}
How to: Create and Attach to Another Instance of Visual Studio
How to: Fix 'Application is Busy' and 'Call was Rejected By Callee'
Errors

Simpler way of doing it.
public static void Attach(DTE2 dte)
{
var processes = dte.Debugger.LocalProcesses;
foreach (var proc in processes.Cast<EnvDTE.Process>().Where(proc => proc.Name.IndexOf("YourProcess.exe") != -1))
proc.Attach();
}
internal static DTE2 GetCurrent()
{
var dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.12.0"); // For VisualStudio 2013
return dte2;
}
Usage:
Attach(GetCurrent());

An option is to run; vsjitdebugger.exe -p ProcessId
It may be possible to use Process.Start to do this within a c# app.

If you have troubles with attaching debugger to process that is too quick to attach manually, don't forget you can sometimes add Console.ReadKey(); to a first line of your code and then you have all the time you need to attach it manually. Surprisingly it took me a while to figure that one out :D

Related

How to change item properties programmatically (Content Processor XNA 4.0 )?

I need to change the content processor of my models programmatically or the fbx file property (XNA Framework Content Pipeline->Content Processor) from the solution/project because of the custom content processor.
And that's all because I want the user who uses this program to add his skinned model and change this property.
Thanks in advance and my apologies if the question is vague or repetitive.
Update
With some research I found a solution sort of for accessing the project but unfortunately getting an error while trying to get the projectitems inside my solution/project .. still can access project properties (haven't tried changing them).
here's the code (which was like MSDN template):
static void Main(string[] args)
{
EnvDTE80.DTE2 dte;
object obj = null;
System.Type t = null;
t = System.Type.GetTypeFromProgID("VisualStudio.DTE.11.0", true);
obj = System.Activator.CreateInstance(t, true);
dte = (EnvDTE80.DTE2)obj;
string solutionFile =
"C:\\Users\\The Wizard Of Code\\Documents\\Visual Studio 2012\\Projects\\ConsoleApplication2\\ConsoleApplication2.sln";
MessageFilter.Register();
//dte.MainWindow.Activate();
/*Problem I think*/
Solution2 soln = (Solution2)dte.Solution;
soln.open(solutionFile);
Console.WriteLine(soln.Item(1).ProjectItems.Item(1).Name);
dte.Quit();
MessageFilter.Revoke();
}
The error message :
The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))
Update 2
Message filter class:
public class MessageFilter : IOleMessageFilter
{
//
// Class containing the IOleMessageFilter
// thread error-handling functions.
// Start the filter.
public static void Register()
{
IOleMessageFilter newFilter = new MessageFilter();
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(newFilter, out oldFilter);
}
// Done with the filter, close it.
public static void Revoke()
{
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(null, out oldFilter);
}
//
// IOleMessageFilter functions.
// Handle incoming thread requests.
int IOleMessageFilter.HandleInComingCall(int dwCallType,
System.IntPtr hTaskCaller, int dwTickCount, System.IntPtr
lpInterfaceInfo)
{
//Return the flag SERVERCALL_ISHANDLED.
return 0;
}
// Thread call was rejected, so try again.
int IOleMessageFilter.RetryRejectedCall(System.IntPtr
hTaskCallee, int dwTickCount, int dwRejectType)
{
if (dwRejectType == 2)
// flag = SERVERCALL_RETRYLATER.
{
// Retry the thread call immediately if return >=0 &
// <100.
return 99;
}
// Too busy; cancel call.
return -1;
}
int IOleMessageFilter.MessagePending(System.IntPtr hTaskCallee,
int dwTickCount, int dwPendingType)
{
//Return the flag PENDINGMSG_WAITDEFPROCESS.
return 2;
}
// Implement the IOleMessageFilter interface.
[DllImport("Ole32.dll")]
private static extern int
CoRegisterMessageFilter(IOleMessageFilter newFilter, out
IOleMessageFilter oldFilter);
}
[ComImport(), Guid("00000016-0000-0000-C000-000000000046"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
interface IOleMessageFilter
{
[PreserveSig]
int HandleInComingCall(
int dwCallType,
IntPtr hTaskCaller,
int dwTickCount,
IntPtr lpInterfaceInfo);
[PreserveSig]
int RetryRejectedCall(
IntPtr hTaskCallee,
int dwTickCount,
int dwRejectType);
[PreserveSig]
int MessagePending(
IntPtr hTaskCallee,
int dwTickCount,
int dwPendingType);
}
sorry for the load of code
Update 3
I managed to get to the properties but they were the file properties not the properties I get when I right click on the item on some project or solution and get that tab on the bottom right (which I need to do through code).
[STAThread]
before main seems to fix the issue
src : http://msdn.developer-works.com/article/11266583/why+looping+through+projectitems+sometimes+causes+Exception+from+HRESULT%3A+0x8001010A+(RPC_E_SERVERCALL_RETRYLATER)....
Update
modelviewer.codeplex.com
had what I needed.

C# Attach Debugger to Another Process in Code at Runtime [duplicate]

I'd like to be able to automatically attach a debugger, something like: System.Diagnostics.Debugger.Launch(), except rather than the current process to another named process. I've got a process name and PID to identify the other process.
Is this possible?
Edit:
GSerjo offered the correct solution. I'd like to share a few thoughts on how to improve it (and an explanation). I hope my improved answer will be useful to to others who experience the same problem.
Attaching the VS Debugger to a Process
Manually
Open the Windows Task Manager (Ctrl + Shift + Esc).
Go to the Tab Processes.
Right click the process.
Select Debug.
Or, within Visual Studio, select Debug > Attach to Process....
Results will vary depending on whether you have access to the source code.
Automatically with C#
A note of caution: The following code is brittle in the sense that certain values,
such as the Visual Studio Version number, are hard-coded. Keep this in mind going forward
if you are planning to distribute your program.
First of all, add a reference to EnvDTE to your project (right click on the references folder in the solution explorer, add reference). In the following code, I'll only show the unusual using directives; the normal ones such as using System are omitted.
Because you are interacting with COM you need to make sure to decorate your Main method (the entry point of your application) with the STAThreadAttribute.
Then, you need to define the IOleMessageFilter Interface that will allow you to interact with the defined COM methods (note the ComImportAttribute). We need to access the message filter so we can retry if the Visual Studio COM component blocks one of our calls.
using System.Runtime.InteropServices;
[ComImport, Guid("00000016-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleMessageFilter
{
[PreserveSig]
int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);
[PreserveSig]
int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);
[PreserveSig]
int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
}
Now, we need to implement this interface in order to handle incoming messages:
public class MessageFilter : IOleMessageFilter
{
private const int Handled = 0, RetryAllowed = 2, Retry = 99, Cancel = -1, WaitAndDispatch = 2;
int IOleMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo)
{
return Handled;
}
int IOleMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
{
return dwRejectType == RetryAllowed ? Retry : Cancel;
}
int IOleMessageFilter.MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
{
return WaitAndDispatch;
}
public static void Register()
{
CoRegisterMessageFilter(new MessageFilter());
}
public static void Revoke()
{
CoRegisterMessageFilter(null);
}
private static void CoRegisterMessageFilter(IOleMessageFilter newFilter)
{
IOleMessageFilter oldFilter;
CoRegisterMessageFilter(newFilter, out oldFilter);
}
[DllImport("Ole32.dll")]
private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter);
}
I defined the return values as constants for better readability and refactored the whole thing a bit to get rid of some of the duplication from the MSDN example, so I hope you'll find it self-explanatory. extern int CoRegisterMessageFilter is our connection to the unmanaged message filter code - you can read up on the extern keyword at MSDN.
Now all that's left is some code illustrating the usage:
using System.Runtime.InteropServices;
using EnvDTE;
[STAThread]
public static void Main()
{
MessageFilter.Register();
var process = GetProcess(7532);
if (process != null)
{
process.Attach();
Console.WriteLine("Attached to {0}", process.Name);
}
MessageFilter.Revoke();
Console.ReadLine();
}
private static Process GetProcess(int processID)
{
var dte = (DTE)Marshal.GetActiveObject("VisualStudio.DTE.10.0");
var processes = dte.Debugger.LocalProcesses.OfType<Process>();
return processes.SingleOrDefault(x => x.ProcessID == processID);
}
Check this out
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using EnvDTE;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
public class ForTest
{
[STAThread]
[Test]
public void Test()
{
var dte = (DTE) Marshal.GetActiveObject("VisualStudio.DTE.10.0");
MessageFilter.Register();
IEnumerable<Process> processes = dte.Debugger.LocalProcesses.OfType<Process>();
var process = processes.SingleOrDefault(x => x.ProcessID == 6152);
if (process != null)
{
process.Attach();
}
}
}
public class MessageFilter : IOleMessageFilter
{
//
// Class containing the IOleMessageFilter
// thread error-handling functions.
// Start the filter.
//
// IOleMessageFilter functions.
// Handle incoming thread requests.
#region IOleMessageFilter Members
int IOleMessageFilter.HandleInComingCall(int dwCallType,
IntPtr hTaskCaller, int dwTickCount, IntPtr
lpInterfaceInfo)
{
//Return the flag SERVERCALL_ISHANDLED.
return 0;
}
// Thread call was rejected, so try again.
int IOleMessageFilter.RetryRejectedCall(IntPtr
hTaskCallee, int dwTickCount, int dwRejectType)
{
if (dwRejectType == 2)
// flag = SERVERCALL_RETRYLATER.
{
// Retry the thread call immediately if return >=0 &
// <100.
return 99;
}
// Too busy; cancel call.
return -1;
}
int IOleMessageFilter.MessagePending(IntPtr hTaskCallee,
int dwTickCount, int dwPendingType)
{
//Return the flag PENDINGMSG_WAITDEFPROCESS.
return 2;
}
#endregion
public static void Register()
{
IOleMessageFilter newFilter = new MessageFilter();
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(newFilter, out oldFilter);
}
// Done with the filter, close it.
public static void Revoke()
{
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(null, out oldFilter);
}
// Implement the IOleMessageFilter interface.
[DllImport("Ole32.dll")]
private static extern int
CoRegisterMessageFilter(IOleMessageFilter newFilter, out
IOleMessageFilter oldFilter);
}
[ComImport, Guid("00000016-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IOleMessageFilter
{
[PreserveSig]
int HandleInComingCall(
int dwCallType,
IntPtr hTaskCaller,
int dwTickCount,
IntPtr lpInterfaceInfo);
[PreserveSig]
int RetryRejectedCall(
IntPtr hTaskCallee,
int dwTickCount,
int dwRejectType);
[PreserveSig]
int MessagePending(
IntPtr hTaskCallee,
int dwTickCount,
int dwPendingType);
}
}
How to: Create and Attach to Another Instance of Visual Studio
How to: Fix 'Application is Busy' and 'Call was Rejected By Callee'
Errors
Simpler way of doing it.
public static void Attach(DTE2 dte)
{
var processes = dte.Debugger.LocalProcesses;
foreach (var proc in processes.Cast<EnvDTE.Process>().Where(proc => proc.Name.IndexOf("YourProcess.exe") != -1))
proc.Attach();
}
internal static DTE2 GetCurrent()
{
var dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.12.0"); // For VisualStudio 2013
return dte2;
}
Usage:
Attach(GetCurrent());
An option is to run; vsjitdebugger.exe -p ProcessId
It may be possible to use Process.Start to do this within a c# app.
If you have troubles with attaching debugger to process that is too quick to attach manually, don't forget you can sometimes add Console.ReadKey(); to a first line of your code and then you have all the time you need to attach it manually. Surprisingly it took me a while to figure that one out :D

Screen.AllScreen is not giving the correct monitor count

I am doing something like this in my program:
Int32 currentMonitorCount = Screen.AllScreens.Length;
if (currentMonitorCount < 2)
{
//Put app in single screen mode.
}
else
{
//Put app in dual screen mode.
}
It is VERY important my application recognizes how many monitors are currently connected.
However, after I plug/unplug the monitor a couple of times, Screen.AllScreens.Length always returns '2'.
My monitor knows it's not connected (it has entered 'power save' mode), and the control panel knows that it's not connected (it shows only one monitor).
So what am I missing? How do I figure out that there's only one monitor?
I had a look at the source (remember we can do that using the MS Symbol servers). AllScreens uses an unmanaged API to get the screens on the first access, then stores the result in a static variable for later use.
The consequence of this, is that if the number of monitors changes while your program is running; then Screen.AllScreens will not pick up the change.
The easiest way to get around this would probably be to call the unmanaged API directly.
(Or you could be evil, and use reflection to set the static screens field to null before asking. Don't do that).
Edit:
If you just need to know the count, check whether you can use System.Windows.Forms.SystemInformation.MonitorCount (as suggested in the comments) before going the P/Invoke route. This calls GetSystemMetrics directly, and it is probably correctly updated.
If you find you need to do it using P/Invoke, here is a complete example that demonstrates the usage of the unmanaged API from C#:
using System;
using System.Runtime.InteropServices;
class Program
{
public static void Main()
{
int monCount = 0;
Rect r = new Rect();
MonitorEnumProc callback = (IntPtr hDesktop, IntPtr hdc, ref Rect prect, int d) => ++monCount > 0;
if (EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, callback, 0))
Console.WriteLine("You have {0} monitors", monCount);
else
Console.WriteLine("An error occured while enumerating monitors");
}
[DllImport("user32")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lpRect, MonitorEnumProc callback, int dwData);
private delegate bool MonitorEnumProc(IntPtr hDesktop, IntPtr hdc, ref Rect pRect, int dwData);
[StructLayout(LayoutKind.Sequential)]
private struct Rect
{
public int left;
public int top;
public int right;
public int bottom;
}
}
Building on the previous reply by driis, this is how I handled it. I should note that the following code lives in my Program.cs file.
First the links to external resources and data structures:
[DllImport("user32")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lpRect, MonitorEnumProc callback, int dwData);
private delegate bool MonitorEnumProc(IntPtr hDesktop, IntPtr hdc, ref Rect pRect, int dwData);
[StructLayout(LayoutKind.Sequential)]
private struct Rect
{
public int left;
public int top;
public int right;
public int bottom;
}
Now create a simple object to contain monitor information:
public class MonitorInfo
{
public bool IsPrimary = false;
public Rectangle Bounds = new Rectangle();
}
And a container to hold these objects:
public static List<MonitorInfo> ActualScreens = new List<MonitorInfo>();
and a method to refresh the container:
public static void RefreshActualScreens()
{
ActualScreens.Clear();
MonitorEnumProc callback = (IntPtr hDesktop, IntPtr hdc, ref Rect prect, int d) =>
{
ActualScreens.Add(new MonitorInfo()
{
Bounds = new Rectangle()
{
X = prect.left,
Y = prect.top,
Width = prect.right - prect.left,
Height = prect.bottom - prect.top,
},
IsPrimary = (prect.left == 0) && (prect.top == 0),
});
return true;
};
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, callback, 0);
}
Then later on a Form, If I wanted to detect that a display had been added or removed ...
private const int WM_DISPLAYCHANGE = 0x007e;
protected override void WndProc(ref Message message)
{
base.WndProc(ref message);
if (message.Msg == WM_DISPLAYCHANGE)
{
Program.RefreshActualScreens();
// do something really interesting here
}
}
Might be a few typos in there, but that is the basic idea. Good luck!
I had a look at the code of the Screen class ( in here )
See line 120, Screen.AllScreens uses the field Screen.screens for cache.
In my solution, I use the reflection api to change the Screen class.
I clear Screens.screens before calling Screen.AllScreens.
// Code for clearing private field
typeof(Screen).GetField("screens", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).SetValue(null, null);

Global Hotkey in Mono and Gtk#

I'm trying to get a global hotkey working in Linux using Mono. I found the signatures of XGrabKey and XUngrabKey, but I can't seem to get them working. Whenever I try to invoke XGrabKey, the application crashes with a SIGSEGV.
This is what I have so far:
using System;
using Gtk;
using System.Runtime.InteropServices;
namespace GTKTest
{
class MainClass
{
const int GrabModeAsync = 1;
public static void Main(string[] args)
{
Application.Init();
MainWindow win = new MainWindow();
win.Show();
// Crashes here
XGrabKey(
win.Display.Handle,
(int)Gdk.Key.A,
(uint)KeyMasks.ShiftMask,
win.Handle,
true,
GrabModeAsync,
GrabModeAsync);
Application.Run();
XUngrabKey(
win.Display.Handle,
(int)Gdk.Key.A,
(uint)KeyMasks.ShiftMask,
win.Handle);
}
[DllImport("libX11")]
internal static extern int XGrabKey(
IntPtr display,
int keycode,
uint modifiers,
IntPtr grab_window,
bool owner_events,
int pointer_mode,
int keyboard_mode);
[DllImport("libX11")]
internal static extern int XUngrabKey(
IntPtr display,
int keycode,
uint modifiers,
IntPtr grab_window);
}
public enum KeyMasks
{
ShiftMask = (1 << 0),
LockMask = (1 << 1),
ControlMask = (1 << 2),
Mod1Mask = (1 << 3),
Mod2Mask = (1 << 4),
Mod3Mask = (1 << 5),
Mod4Mask = (1 << 6),
Mod5Mask = (1 << 7)
}
}
Does anyone have a working example of XGrabKey?
Thanks!
Well, I finally found a working solution in managed code. The SIGSEGV was happening because I was confusing the handles of the unmanaged Gdk objects with the handles of their X11 counterparts. Thanks to Paul's answer, I was able to find an unmanaged example of global hotkeys and familiarized myself with how it worked. Then I wrote my own unmanaged test program to find out what I needed to do without having to deal with any managed idiosyncrasies. After that was successful, I created a managed solution.
Here is the managed solution:
public class X11Hotkey
{
private const int KeyPress = 2;
private const int GrabModeAsync = 1;
private Gdk.Key key;
private Gdk.ModifierType modifiers;
private int keycode;
public X11Hotkey(Gdk.Key key, Gdk.ModifierType modifiers)
{
this.key = key;
this.modifiers = modifiers;
Gdk.Window rootWin = Gdk.Global.DefaultRootWindow;
IntPtr xDisplay = GetXDisplay(rootWin);
this.keycode = XKeysymToKeycode(xDisplay, (int)this.key);
rootWin.AddFilter(new Gdk.FilterFunc(FilterFunction));
}
public event EventHandler Pressed;
public void Register()
{
Gdk.Window rootWin = Gdk.Global.DefaultRootWindow;
IntPtr xDisplay = GetXDisplay(rootWin);
XGrabKey(
xDisplay,
this.keycode,
(uint)this.modifiers,
GetXWindow(rootWin),
false,
GrabModeAsync,
GrabModeAsync);
}
public void Unregister()
{
Gdk.Window rootWin = Gdk.Global.DefaultRootWindow;
IntPtr xDisplay = GetXDisplay(rootWin);
XUngrabKey(
xDisplay,
this.keycode,
(uint)this.modifiers,
GetXWindow(rootWin));
}
private Gdk.FilterReturn FilterFunction(IntPtr xEvent, Gdk.Event evnt)
{
XKeyEvent xKeyEvent = (XKeyEvent)Marshal.PtrToStructure(
xEvent,
typeof(XKeyEvent));
if (xKeyEvent.type == KeyPress)
{
if (xKeyEvent.keycode == this.keycode
&& xKeyEvent.state == (uint)this.modifiers)
{
this.OnPressed(EventArgs.Empty);
}
}
return Gdk.FilterReturn.Continue;
}
protected virtual void OnPressed(EventArgs e)
{
EventHandler handler = this.Pressed;
if (handler != null)
{
handler(this, e);
}
}
private static IntPtr GetXWindow(Gdk.Window window)
{
return gdk_x11_drawable_get_xid(window.Handle);
}
private static IntPtr GetXDisplay(Gdk.Window window)
{
return gdk_x11_drawable_get_xdisplay(
gdk_x11_window_get_drawable_impl(window.Handle));
}
[DllImport("libgtk-x11-2.0")]
private static extern IntPtr gdk_x11_drawable_get_xid(IntPtr gdkWindow);
[DllImport("libgtk-x11-2.0")]
private static extern IntPtr gdk_x11_drawable_get_xdisplay(IntPtr gdkDrawable);
[DllImport("libgtk-x11-2.0")]
private static extern IntPtr gdk_x11_window_get_drawable_impl(IntPtr gdkWindow);
[DllImport("libX11")]
private static extern int XKeysymToKeycode(IntPtr display, int key);
[DllImport("libX11")]
private static extern int XGrabKey(
IntPtr display,
int keycode,
uint modifiers,
IntPtr grab_window,
bool owner_events,
int pointer_mode,
int keyboard_mode);
[DllImport("libX11")]
private static extern int XUngrabKey(
IntPtr display,
int keycode,
uint modifiers,
IntPtr grab_window);
#if BUILD_FOR_32_BIT_X11
[StructLayout(LayoutKind.Sequential)]
internal struct XKeyEvent
{
public short type;
public uint serial;
public short send_event;
public IntPtr display;
public uint window;
public uint root;
public uint subwindow;
public uint time;
public int x, y;
public int x_root, y_root;
public uint state;
public uint keycode;
public short same_screen;
}
#elif BUILD_FOR_64_BIT_X11
[StructLayout(LayoutKind.Sequential)]
internal struct XKeyEvent
{
public int type;
public ulong serial;
public int send_event;
public IntPtr display;
public ulong window;
public ulong root;
public ulong subwindow;
public ulong time;
public int x, y;
public int x_root, y_root;
public uint state;
public uint keycode;
public int same_screen;
}
#endif
}
And here is the test program:
public static void Main (string[] args)
{
Application.Init();
X11Hotkey hotkey = new X11Hotkey(Gdk.Key.A, Gdk.ModifierType.ControlMask);
hotkey.Pressed += HotkeyPressed;;
hotkey.Register();
Application.Run();
hotkey.Unregister();
}
private static void HotkeyPressed(object sender, EventArgs e)
{
Console.WriteLine("Hotkey Pressed!");
}
I'm not sure how the XKeyEvent structure will behave on other systems with different sizes for C ints and longs, so whether this solution will work on all systems remains to be seen.
Edit: It looks like this solution is not going to be architecture-independent as I feared, due to the varying nature of the underlying C type sizes. libgtkhotkey looks promising as way to avoid deploying and compiling custom unmanaged libraries with your managed assemblies.
Note: Now you need to explicity define BUILD_FOR_32_BIT_X11 or BUILD_FOR_64_BIT_X11 depending on the word-size of your OS.
I'm new to this site and it seems that I can't leave a comment on a previous question as I have insufficient reputation. (Sorry I can't even up-vote you!)
Relating to the issue of differing underlying sizes, I think this is solvable by using an IntPtr for the longs. This follows a suggestion in the Mono project documentation, see http://www.mono-project.com/Interop_with_Native_Libraries#Longs. The C types int and Bool should map to C# int.
Regarding the GAPI wrapper, I tried it, but couldn't get it working. If Zach could post any info on how he did it, I'd be grateful.
Also I couldn't get the sample program to work. Like SDX2000, I had to edit the library names, and I added using statements. I had a problem with Application.Init(), which in the end I swapped for creating a Form. But still my register call fails with BadRequest. If anyone who has got this working can update the code to make it more complete I'd be grateful.
Tomboy has some code that knows how to do this, I'd take the code from there.

Service not fully stopped after ServiceController.Stop()

ServiceController serviceController = new ServiceController(someService);
serviceController.Stop();
serviceController.WaitForStopped();
DoSomething();
SomeService works on a sqlserver file. DoSomething() wants to copy that SQL file. If SomeService isn't closed fully it will throw an error because the database file is still locked. In the aforementioned code, I get past the WaitForStopped() method and yet the service doesn't release the database file until after DoSomething(), thus I get an error.
Doing some more investigation, I find that before the DoSomething method call I see that the service controller status shows a stopped and yet looking at some ProcMon logs the service releases the database file after I'm thrown an error from DoSomething.
Also, if I put a Thread.Sleep between the WaitForStopped and the DoSomething method for say... 5 seconds, the database file is released and all is well. Not the solution of surety I'm looking for however.
Any ideas?
Windows Services are a layer on top of processes; in order to be a service, an application must connect to the Service Control Manager and announce which services are available. This connection is handled within the ADVAPI32.DLL library. Once this connection is established, the library maintains a thread waiting for commands from the Service Control Manager, which can then start and stop services arbitrarily. I don't believe the process is required to exit when the last service in it terminates. Though that is what typically happens, the end of the link with the Service Control Manager, which occurs after the last service enters the "Stopped" state, can occur significantly before the process actually terminates, releasing any resources it hasn't already explicitly released.
The Windows Service API includes functionality that lets you obtain the Process ID of the process that is hosting the service. It is possible for a single process to host many services, and so the process might not actually exit when the service you are interested in has terminated, but you should be safe with SQL Server. Unfortunately, the .NET Framework does not expose this functionality. It does, however, expose the handle to the service that it uses internally for API calls, and you can use it to make your own API calls. With a bit of P/Invoke, then, you can obtain the process ID of the Windows Service process, and from there, provided you have the necessary permission, you can open a handle to the process that can be used to wait for it to exit.
Something like this:
[DllImport("advapi32")]
static extern bool QueryServiceStatusEx(IntPtr hService, int InfoLevel, ref SERVICE_STATUS_PROCESS lpBuffer, int cbBufSize, out int pcbBytesNeeded);
const int SC_STATUS_PROCESS_INFO = 0;
[StructLayout(LayoutKind.Sequential)]
struct SERVICE_STATUS_PROCESS
{
public int dwServiceType;
public int dwCurrentState;
public int dwControlsAccepted;
public int dwWin32ExitCode;
public int dwServiceSpecificExitCode;
public int dwCheckPoint;
public int dwWaitHint;
public int dwProcessId;
public int dwServiceFlags;
}
const int SERVICE_WIN32_OWN_PROCESS = 0x00000010;
const int SERVICE_INTERACTIVE_PROCESS = 0x00000100;
const int SERVICE_RUNS_IN_SYSTEM_PROCESS = 0x00000001;
public static void StopServiceAndWaitForExit(string serviceName)
{
using (ServiceController controller = new ServiceController(serviceName))
{
SERVICE_STATUS_PROCESS ssp = new SERVICE_STATUS_PROCESS();
int ignored;
// Obtain information about the service, and specifically its hosting process,
// from the Service Control Manager.
if (!QueryServiceStatusEx(controller.ServiceHandle.DangerousGetHandle(), SC_STATUS_PROCESS_INFO, ref ssp, Marshal.SizeOf(ssp), out ignored))
throw new Exception("Couldn't obtain service process information.");
// A few quick sanity checks that what the caller wants is *possible*.
if ((ssp.dwServiceType & ~SERVICE_INTERACTIVE_PROCESS) != SERVICE_WIN32_OWN_PROCESS)
throw new Exception("Can't wait for the service's hosting process to exit because there may be multiple services in the process (dwServiceType is not SERVICE_WIN32_OWN_PROCESS");
if ((ssp.dwServiceFlags & SERVICE_RUNS_IN_SYSTEM_PROCESS) != 0)
throw new Exception("Can't wait for the service's hosting process to exit because the hosting process is a critical system process that will not exit (SERVICE_RUNS_IN_SYSTEM_PROCESS flag set)");
if (ssp.dwProcessId == 0)
throw new Exception("Can't wait for the service's hosting process to exit because the process ID is not known.");
// Note: It is possible for the next line to throw an ArgumentException if the
// Service Control Manager's information is out-of-date (e.g. due to the process
// having *just* been terminated in Task Manager) and the process does not really
// exist. This is a race condition. The exception is the desirable result in this
// case.
using (Process process = Process.GetProcessById(ssp.dwProcessId))
{
// EDIT: There is no need for waiting in a separate thread, because MSDN says "The handles are valid until closed, even after the process or thread they represent has been terminated." ( http://msdn.microsoft.com/en-us/library/windows/desktop/ms684868%28v=vs.85%29.aspx ), so to keep things in the same thread, the process HANDLE should be opened from the process id before the service is stopped, and the Wait should be done after that.
// Response to EDIT: What you report is true, but the problem is that the handle isn't actually opened by Process.GetProcessById. It's only opened within the .WaitForExit method, which won't return until the wait is complete. Thus, if we try the wait on the current therad, we can't actually do anything until it's done, and if we defer the check until after the process has completed, it won't be possible to obtain a handle to it any more.
// The actual wait, using process.WaitForExit, opens a handle with the SYNCHRONIZE
// permission only and closes the handle before returning. As long as that handle
// is open, the process can be monitored for termination, but if the process exits
// before the handle is opened, it is no longer possible to open a handle to the
// original process and, worse, though it exists only as a technicality, there is
// a race condition in that another process could pop up with the same process ID.
// As such, we definitely want the handle to be opened before we ask the service
// to close, but since the handle's lifetime is only that of the call to WaitForExit
// and while WaitForExit is blocking the thread we can't make calls into the SCM,
// it would appear to be necessary to perform the wait on a separate thread.
ProcessWaitForExitData threadData = new ProcessWaitForExitData();
threadData.Process = process;
Thread processWaitForExitThread = new Thread(ProcessWaitForExitThreadProc);
processWaitForExitThread.IsBackground = Thread.CurrentThread.IsBackground;
processWaitForExitThread.Start(threadData);
// Now we ask the service to exit.
controller.Stop();
// Instead of waiting until the *service* is in the "stopped" state, here we
// wait for its hosting process to go away. Of course, it's really that other
// thread waiting for the process to go away, and then we wait for the thread
// to go away.
lock (threadData.Sync)
while (!threadData.HasExited)
Monitor.Wait(threadData.Sync);
}
}
}
class ProcessWaitForExitData
{
public Process Process;
public volatile bool HasExited;
public object Sync = new object();
}
static void ProcessWaitForExitThreadProc(object state)
{
ProcessWaitForExitData threadData = (ProcessWaitForExitData)state;
try
{
threadData.Process.WaitForExit();
}
catch {}
finally
{
lock (threadData.Sync)
{
threadData.HasExited = true;
Monitor.PulseAll(threadData.Sync);
}
}
}
ServiceController.WaitForStopped()/WaitForStatus() will return once the service implementation claims it has stopped. This doesn't necessary mean the process has released all of its resources and has exited. I've seen database other than SQL Server do this as well.
If you really want to be sure the database is fully and truly stopped, you will have to interface with the database itself, get ahold of the process id and wait for it to exit, wait for locks on the files to be released, ...
In my case I have used the interops:
[StructLayout(LayoutKind.Sequential)]
public struct SC_HANDLE__
{
public int unused;
}
[Flags]
public enum SERVICE_CONTROL : uint
{
STOP = 0x00000001,
PAUSE = 0x00000002,
CONTINUE = 0x00000003,
INTERROGATE = 0x00000004,
SHUTDOWN = 0x00000005,
PARAMCHANGE = 0x00000006,
NETBINDADD = 0x00000007,
NETBINDREMOVE = 0x00000008,
NETBINDENABLE = 0x00000009,
NETBINDDISABLE = 0x0000000A,
DEVICEEVENT = 0x0000000B,
HARDWAREPROFILECHANGE = 0x0000000C,
POWEREVENT = 0x0000000D,
SESSIONCHANGE = 0x0000000E
}
[StructLayout(LayoutKind.Sequential)]
public struct SERVICE_STATUS
{
/// DWORD->unsigned int
public uint dwServiceType;
/// DWORD->unsigned int
public uint dwCurrentState;
/// DWORD->unsigned int
public uint dwControlsAccepted;
/// DWORD->unsigned int
public uint dwWin32ExitCode;
/// DWORD->unsigned int
public uint dwServiceSpecificExitCode;
/// DWORD->unsigned int
public uint dwCheckPoint;
/// DWORD->unsigned int
public uint dwWaitHint;
}
public class NativeMethods
{
public const int SC_MANAGER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED
| (SC_MANAGER_CONNECT
| (SC_MANAGER_CREATE_SERVICE
| (SC_MANAGER_ENUMERATE_SERVICE
| (SC_MANAGER_LOCK
| (SC_MANAGER_QUERY_LOCK_STATUS | SC_MANAGER_MODIFY_BOOT_CONFIG))))));
/// STANDARD_RIGHTS_REQUIRED -> (0x000F0000L)
public const int STANDARD_RIGHTS_REQUIRED = 983040;
/// SC_MANAGER_CONNECT -> 0x0001
public const int SC_MANAGER_CONNECT = 1;
/// SC_MANAGER_CREATE_SERVICE -> 0x0002
public const int SC_MANAGER_CREATE_SERVICE = 2;
/// SC_MANAGER_ENUMERATE_SERVICE -> 0x0004
public const int SC_MANAGER_ENUMERATE_SERVICE = 4;
/// SC_MANAGER_LOCK -> 0x0008
public const int SC_MANAGER_LOCK = 8;
/// SC_MANAGER_QUERY_LOCK_STATUS -> 0x0010
public const int SC_MANAGER_QUERY_LOCK_STATUS = 16;
/// SC_MANAGER_MODIFY_BOOT_CONFIG -> 0x0020
public const int SC_MANAGER_MODIFY_BOOT_CONFIG = 32;
/// SERVICE_CONTROL_STOP -> 0x00000001
public const int SERVICE_CONTROL_STOP = 1;
/// SERVICE_QUERY_STATUS -> 0x0004
public const int SERVICE_QUERY_STATUS = 4;
public const int GENERIC_EXECUTE = 536870912;
/// SERVICE_RUNNING -> 0x00000004
public const int SERVICE_RUNNING = 4;
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess);
[DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW")]
public static extern IntPtr OpenSCManagerW(
[In()] [MarshalAs(UnmanagedType.LPWStr)] string lpMachineName,
[In()] [MarshalAs(UnmanagedType.LPWStr)] string lpDatabaseName,
uint dwDesiredAccess);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ControlService(IntPtr hService, SERVICE_CONTROL dwControl, ref SERVICE_STATUS lpServiceStatus);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseServiceHandle(IntPtr hSCObject);
[DllImport("advapi32.dll", EntryPoint = "QueryServiceStatus", CharSet = CharSet.Auto)]
public static extern bool QueryServiceStatus(IntPtr hService, ref SERVICE_STATUS dwServiceStatus);
[SecurityCritical]
[HandleProcessCorruptedStateExceptions]
public static void ServiceStop()
{
IntPtr manager = IntPtr.Zero;
IntPtr service = IntPtr.Zero;
SERVICE_STATUS status = new SERVICE_STATUS();
if ((manager = OpenSCManagerW(null, null, SC_MANAGER_ALL_ACCESS)) != IntPtr.Zero)
{
if ((service = OpenService(manager, Resources.ServiceName, SC_MANAGER_ALL_ACCESS)) != IntPtr.Zero)
{
QueryServiceStatus(service, ref status);
}
if (status.dwCurrentState == SERVICE_RUNNING)
{
int i = 0;
//not the best way, but WaitStatus didnt work correctly.
while (i++ < 10 && status.dwCurrentState != SERVICE_CONTROL_STOP)
{
ControlService(service, SERVICE_CONTROL.STOP, ref status);
QueryServiceStatus(service, ref status);
Thread.Sleep(200);
}
}
}
if (manager != IntPtr.Zero)
{
var b = CloseServiceHandle(manager);
}
if (service != IntPtr.Zero)
{
var b = CloseServiceHandle(service);
}
}
}
I've seen this before when I stopped a service that was a dependency to another service, and the second service was holding resources I didn't even know it was using. Do you think this might be the case? I know SQL has quite a few different components, but I haven't looked into whether there are multiple services associated with it.
Good luck!
Even using #Jonathan Gilbert excellent answer I still had cases where I could not delete the service executable file after the service process was stopped. I found out I had to also call process.Kill() at the end of it all to totally free resources.
Here is a version of Jonathan Gilbert answer which adds Kill, a timeout, and better thread synchronization:
namespace System.ServiceProcess {
public static class ExtensionMethods {
[DllImport("advapi32")]
static extern bool QueryServiceStatusEx(IntPtr hService, int InfoLevel, ref SERVICE_STATUS_PROCESS lpBuffer, int cbBufSize, out int pcbBytesNeeded);
[StructLayout(LayoutKind.Sequential)] struct SERVICE_STATUS_PROCESS { public int dwServiceType; public int dwCurrentState; public int dwControlsAccepted; public int dwWin32ExitCode; public int dwServiceSpecificExitCode; public int dwCheckPoint; public int dwWaitHint; public int dwProcessId; public int dwServiceFlags; }
const int SC_STATUS_PROCESS_INFO = 0, SERVICE_WIN32_OWN_PROCESS = 0x00000010, SERVICE_INTERACTIVE_PROCESS = 0x00000100, SERVICE_RUNS_IN_SYSTEM_PROCESS = 0x00000001;
record ProcessWaitForExitData(int ProcessId, AutoResetEvent MWaitForThread, int TimeoutMilliseconds);
// wait for the actual process that runs the service to stop
public static void StopAndWaitForProcessToExit(this ServiceController controller, int timeoutMilliseconds=-1) {
var processId = -1;
try {
var ssp = new SERVICE_STATUS_PROCESS();
// check can't obtain service process informatio
if (QueryServiceStatusEx(controller.ServiceHandle.DangerousGetHandle(), SC_STATUS_PROCESS_INFO, ref ssp, Marshal.SizeOf(ssp), out int ignored)
// check can't wait for the service's hosting process to exit because there may be multiple services in the process (dwServiceType is not SERVICE_WIN32_OWN_PROCESS)
&& (ssp.dwServiceType & ~SERVICE_INTERACTIVE_PROCESS) == SERVICE_WIN32_OWN_PROCESS
// check can't wait for the service's hosting process to exit because the hosting process is a critical system process that will not exit (SERVICE_RUNS_IN_SYSTEM_PROCESS flag set)");
&& (ssp.dwServiceFlags & SERVICE_RUNS_IN_SYSTEM_PROCESS) == 0
// chec can't wait for the service's hosting process to exit because the process ID is not known.");
&& ssp.dwProcessId != 0) processId = ssp.dwProcessId;
} catch (Exception) {
}
if (processId==-1) {
controller.Stop(); // stop the service
return; // we did all we can
}
// we need to call WaitForExit before stopping the service so we do it in a separate thread
var mWaitForThread = new AutoResetEvent(false);
var processWaitForExitThread = new Thread(ProcessWaitForExitThreadProc) { IsBackground = Thread.CurrentThread.IsBackground };
processWaitForExitThread.Start(new ProcessWaitForExitData(processId, mWaitForThread, timeoutMilliseconds));
Task.Delay(5).Wait(); // let thread reach WaitForExit, is there a better way ?
controller.Stop(); // stop the service
mWaitForThread.WaitOne(); // wait for process to exit
}
static void ProcessWaitForExitThreadProc(object? state) {
ProcessWaitForExitData threadData = (ProcessWaitForExitData)state!;
try {
using Process process = Process.GetProcessById(threadData.ProcessId);
var stopwatch = Stopwatch.StartNew();
process.WaitForExit(threadData.TimeoutMilliseconds);
process.Kill(true); // free all process resources
var killTimeout = threadData.TimeoutMilliseconds==-1 ? -1 : (int)Math.Max(threadData.TimeoutMilliseconds - stopwatch.ElapsedMilliseconds, 10);
if (!process.WaitForExit(killTimeout)) throw new TimeoutException();
}
catch { }
finally {
threadData.MWaitForThread.Set();
}
}
}
}
To use:
using ServiceController controller = new(serviceName);
controller.StopAndWaitForProcessToExit(timeoutMilliseconds);
Try to use Environment.Exit(1);

Categories

Resources