Related
I'm trying to get a list of selected files from the Desktop. I get the correct amount of files, but I get weird file names like this for example: 㺘ݔ䁐\u0086\u0002. I'm using the LVM_GETITEM message to get the info. This is my code:
public string GetItemText(int idx)
{
const int MAX_SIZE = 512;
byte[] szBuffer = new byte[MAX_SIZE];
LVITEM lvi = new LVITEM
{
mask = LVIF_TEXT,
cchTextMax = MAX_SIZE,
iItem = idx,
iSubItem = 0,
pszText = Marshal.AllocHGlobal(MAX_SIZE)
};
// Fill LVITEM structure
IntPtr ptrLvi = Marshal.AllocHGlobal(Marshal.SizeOf(lvi));
Marshal.StructureToPtr(lvi, ptrLvi, false);
int readBytes = 0;
try
{
readBytes = SendMessagePtr(ShellListViewHandle, LVM_GETITEM, IntPtr.Zero, ptrLvi);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
// Get the text
string itemText = Marshal.PtrToStringAuto(lvi.pszText);
return itemText;
}
You cannot do that using the Shell Objects for Scripting AFAIK. You can only start with it and then use native Shell interfaces.
This principles are explained here Manipulating the positions of desktop icons in C/C++.
Here is a similar C# Console app that dumps out all items names currently selected in the desktop, you'll have to adapt or expand depending on what you need:
public class Program
{
static void Main()
{
// we basically follow https://devblogs.microsoft.com/oldnewthing/20130318-00/?p=4933
dynamic app = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
var windows = app.Windows;
const int SWC_DESKTOP = 8;
const int SWFO_NEEDDISPATCH = 1;
var hwnd = 0;
var disp = windows.FindWindowSW(Type.Missing, Type.Missing, SWC_DESKTOP, ref hwnd, SWFO_NEEDDISPATCH);
var sp = (IServiceProvider)disp;
var SID_STopLevelBrowser = new Guid("4c96be40-915c-11cf-99d3-00aa004ae837");
var browser = (IShellBrowser)sp.QueryService(SID_STopLevelBrowser, typeof(IShellBrowser).GUID);
var view = (IFolderView)browser.QueryActiveShellView();
view.Items(SVGIO.SVGIO_SELECTION, typeof(IShellItemArray).GUID, out var items);
if (items is IShellItemArray array)
{
for (var i = 0; i < array.GetCount(); i++)
{
var item = array.GetItemAt(i);
Console.WriteLine(item.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY));
}
}
}
[Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.IUnknown)]
object QueryService([MarshalAs(UnmanagedType.LPStruct)] Guid service, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
}
// note: for the following interfaces, not all methods are defined as we don't use them here
[Guid("000214E2-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellBrowser
{
void _VtblGap1_12(); // skip 12 methods https://stackoverflow.com/a/47567206/403671
[return: MarshalAs(UnmanagedType.IUnknown)]
object QueryActiveShellView();
}
[Guid("cde725b0-ccc9-4519-917e-325d72fab4ce"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFolderView
{
void _VtblGap1_5(); // skip 5 methods
[PreserveSig]
int Items(SVGIO uFlags, Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object items);
}
[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem
{
[return: MarshalAs(UnmanagedType.IUnknown)]
object BindToHandler(System.Runtime.InteropServices.ComTypes.IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid bhid, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
IShellItem GetParent();
[return: MarshalAs(UnmanagedType.LPWStr)]
string GetDisplayName(SIGDN sigdnName);
// 2 other methods to be defined
}
[Guid("b63ea76d-1f85-456f-a19c-48159efa858b"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItemArray
{
void _VtblGap1_4(); // skip 4 methods
int GetCount();
IShellItem GetItemAt(int dwIndex);
}
private enum SIGDN
{
SIGDN_NORMALDISPLAY,
SIGDN_PARENTRELATIVEPARSING,
SIGDN_DESKTOPABSOLUTEPARSING,
SIGDN_PARENTRELATIVEEDITING,
SIGDN_DESKTOPABSOLUTEEDITING,
SIGDN_FILESYSPATH,
SIGDN_URL,
SIGDN_PARENTRELATIVEFORADDRESSBAR,
SIGDN_PARENTRELATIVE,
SIGDN_PARENTRELATIVEFORUI
}
private enum SVGIO
{
SVGIO_BACKGROUND,
SVGIO_SELECTION,
SVGIO_ALLVIEW,
SVGIO_CHECKED,
SVGIO_TYPE_MASK,
SVGIO_FLAG_VIEWORDER
}
}
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
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
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);
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);