I have a problem retrieving the information of printer ports. I already use XcvData function to add, configure and delete ports, but I can not get the following to run as I expect it to:
public PrinterNativeMethods.PORT_DATA_1 GetPortData1FromPort(string serverName, string portName)
{
IntPtr printerHandle;
PrinterNativeMethods.PRINTER_DEFAULTS defaults = new PrinterNativeMethods.PRINTER_DEFAULTS
{
DesiredAccess = PrinterNativeMethods.PrinterAccess.ServerAdmin
};
string connection = string.Format(#"{0},XcvPort {1}", serverName, portName);
PrinterNativeMethods.OpenPrinter(connection, out printerHandle, ref defaults);
PrinterNativeMethods.CONFIG_INFO_DATA_1 configData = new PrinterNativeMethods.CONFIG_INFO_DATA_1
{
dwVersion = 1,
};
uint size = (uint)Marshal.SizeOf(configData);
IntPtr pointer = Marshal.AllocHGlobal((int)size);
Marshal.StructureToPtr(configData, pointer, true);
PrinterNativeMethods.PORT_DATA_1 portData = new PrinterNativeMethods.PORT_DATA_1();
uint portDataSize = (uint)Marshal.SizeOf(portData);
IntPtr portDataHandle = Marshal.AllocHGlobal((int)portDataSize);
try
{
uint outputNeeded;
uint status;
var retVal = PrinterNativeMethods.XcvData(printerHandle, "GetConfigInfo", pointer, size, out portDataHandle, portDataSize, out outputNeeded, out status);
//portDataHandle now points to a different location!? Unmarshalling will fail:
portData = (PrinterNativeMethods.PORT_DATA_1)Marshal.PtrToStructure(portDataHandle, typeof(PrinterNativeMethods.PORT_DATA_1));
}
finally
{
PrinterNativeMethods.ClosePrinter(printerHandle);
Marshal.FreeHGlobal(pointer);
Marshal.FreeHGlobal(portDataHandle);
}
return portData;
}
from PrinterNativeMethods:
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern int XcvData(
IntPtr handle,
string dataName,
IntPtr inputData,
uint inputDataSize,
out IntPtr outputData,
uint outputDataSize,
out uint outputNeededSize,
out uint status);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct PORT_DATA_1
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string sztPortName;
public uint dwVersion;
public uint dwProtocol;
public uint cbSize;
public uint dwReserved;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 49)]
public string sztHostAddress;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 33h)]
public string sztSNMPCommunity;
public uint dwDoubleSpool;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 33)]
public string sztQueue;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string sztIPAddress;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 540)]
public byte[] Reserved;
public uint dwPortNumber;
public uint dwSNMPEnabled;
public uint dwSNMPDevIndex;
}
Additional comment: I cannot use WMI or prnadmin.dll as an alternative.
The problem you are having is in the definition of your XcvData definition. The outputData parameter by MS's definition is simply wanting a pointer to write data to, an IntPtr is a pointer, however by setting the parameter to out IntPtr you are making it a pointer to a pointer, this is why the address of your parameter appears to be changing. Changing the signature to the below will fix your problem.
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern int XcvData(
IntPtr handle,
string dataName,
IntPtr inputData,
uint inputDataSize,
IntPtr outputData,
uint outputDataSize,
out uint outputNeededSize,
out uint status);
You can also avoid some unnecessary allocation/deallocation by changing things around a bit.
Change your method signature for XcvData to
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern int XcvData(
IntPtr handle,
string dataName,
IntPtr inputData,
uint inputDataSize,
ref PORT_DATA_1 outputData,
uint outputDataSize,
out uint outputNeededSize,
out uint status);
Assuming that you will be using XcvData for more than just this single call you can make multiple references to it with slightly different signatures by setting the EntryPoint property on the DllImport Attribute.
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint="XcvData")]
internal static extern int XcvDataGetPortData1(
IntPtr handle,
string dataName,
IntPtr inputData,
uint inputDataSize,
ref PORT_DATA_1 outputData,
uint outputDataSize,
out uint outputNeededSize,
out uint status);
I have given this a quick test on my machine and can confirm that this will fix your problem.
Related
I am trying to write C# code that, running in an elevated process, creates a non-elevated process. The (only) answer to the SO question How to call CreateProcess() with STARTUPINFOEX from C# and re-parent the child contains ready-to-use code. I copied this code, but instead of creating a process, it throws an AccessViolationException. The exception text Attempted to read or write protected memory. This is often an indication that other memory is corrupt. does not help to identify the culprit, however from low-level debugging I can see that the processor is trying to read from memory at a very small address like 0x00000004 which, of course, goes wrong.
The code, briefly explained, retrieves a handle of the desktop process, then calls InitializeProcThreadAttributeList and UpdateProcThreadAttribute to initialize the respective fields of a STARTUPINFOEX struct which is then passed into the CreateProcess Windows API function. CreateProcess should then create the new process as a child of the desktop process.
This function expects in its 9th parameter a pointer to either a STARTUPINFO or a STARTUPINFOEX (which contains a STATUPINFO at its begin). If it's a STARTUPINFOEX, the 6th parameter should contain the EXTENDED_STARTUPINFO_PRESENT flag.
When I don't pass the EXTENDED_STARTUPINFO_PRESENT flag so that CreateProcess think it's being passed just a STARTUPINFO, all works fine except that the created process is elevated (as is the calling process). However, as soon as I add this flag, the access violation occurs. For hours I have tried modifying parameter attributes etc., but the problem persists. I have the essentially same code running in C++, so I know it can work. What am I doing wrong?
The code below doesn't contain elaborated error checking, but it should compile and demonstrate the problem out of the box.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace RunNonElevatedCSharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
StartNonElevated(#"C:\WINDOWS\system32\cmd.exe", "");
}
public static int StartNonElevated(string strAppPath, string strCommandLine)
{
bool bSuccess = false;
IntPtr hShellProcess = IntPtr.Zero;
var pInfo = new PROCESS_INFORMATION();
var sInfoEx = new STARTUPINFOEX();
sInfoEx.StartupInfo.cb = Marshal.SizeOf(sInfoEx);
try
{
IntPtr hShellWnd = GetShellWindow();
if (hShellWnd == IntPtr.Zero)
{
return 0;
}
UInt32 pid;
if (GetWindowThreadProcessId(hShellWnd, out pid) == 0)
{
return 0;
}
hShellProcess = OpenProcess(PROCESS_CREATE_PROCESS, FALSE, pid);
if (hShellProcess == IntPtr.Zero)
{
return 0;
}
IntPtr nBufferSize = IntPtr.Zero;
InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref nBufferSize);
if (nBufferSize == IntPtr.Zero)
{
return 0;
}
sInfoEx.lpAttributeList = Marshal.AllocHGlobal(nBufferSize);
if (sInfoEx.lpAttributeList == IntPtr.Zero)
{
return 0;
}
if (!InitializeProcThreadAttributeList(sInfoEx.lpAttributeList, 1, 0, ref nBufferSize))
{
return 0;
}
if (!UpdateProcThreadAttribute(sInfoEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, hShellProcess, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero))
{
return 0;
}
// s1 and s2 may not be required
string s1 = "" + strAppPath + "";
string s2 = "";
// The next line causes an access violation unless you remove the 'EXTENDED_STARTUPINFO_PRESENT' flag
if (!CreateProcess(s1, s2, IntPtr.Zero, IntPtr.Zero, false, CREATE_NEW_CONSOLE | EXTENDED_STARTUPINFO_PRESENT | 0,
IntPtr.Zero, null, ref sInfoEx, out pInfo))
{
return 0;
}
bSuccess = true;
CloseHandle(pInfo.hThread);
CloseHandle(pInfo.hProcess);
return pInfo.dwProcessId;
}
finally
{
if (!bSuccess)
{
var lastError = Marshal.GetLastWin32Error();
Debug.WriteLine("Error: " + lastError.ToString());
}
if (sInfoEx.lpAttributeList != IntPtr.Zero)
{
DeleteProcThreadAttributeList(sInfoEx.lpAttributeList);
Marshal.FreeHGlobal(sInfoEx.lpAttributeList);
}
if (hShellProcess != IntPtr.Zero)
CloseHandle(hShellProcess);
}
}
[DllImport("User32.dll", SetLastError = true)]
public static extern IntPtr GetShellWindow();
[DllImport("User32.dll", SetLastError = true)]
public static extern UInt32 GetWindowThreadProcessId(IntPtr hWnd, out UInt32 lpdwProcessId);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, int bInheritHandle, UInt32 dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)][return: MarshalAs(UnmanagedType.Bool)]
public static extern bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UpdateProcThreadAttribute(IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute, IntPtr lpValue, IntPtr cbSize,
IntPtr lpPreviousValue, IntPtr lpReturnSize);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "CreateProcessW", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CreateProcess(string lpApplicationName, string lpCommandLine,
[In, Optional] IntPtr lpProcessAttributes, [In, Optional] IntPtr lpThreadAttributes,
bool bInheritHandles, uint dwCreationFlags,
[In, Optional] IntPtr lpEnvironment, [In, Optional] string lpCurrentDirectory,
[In] ref STARTUPINFOEX lpStartupInfo, [Out] out PROCESS_INFORMATION lpProcessInformation);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern int CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
private static extern void DeleteProcThreadAttributeList(IntPtr lpAttributeList);
public const UInt32 PROCESS_CREATE_PROCESS = 0x0080;
public const int FALSE = 0;
public const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000;
public const uint CREATE_NEW_CONSOLE = 0x00000010;
public const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFOEX
{
public STARTUPINFO StartupInfo;
public IntPtr lpAttributeList;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
}
When the access violation occurs, the program cannot continue; the "finally" block isn't executed.
Looking forward to any replies...
Hans
Your call to UpdateProcThreadAttribute() is wrong. The 4th parameter needs the address of hShellProcess, not the value. This is even stated as much in this answer to the other question you linked to (the code in the other question has the same bug):
Second, the lpValue parameter of the UpdateProcThreadAttribute function must be a pointer to the attribute value (in your case, parentHandle), not the value itself.
The documentation for PROC_THREAD_ATTRIBUTE_PARENT_PROCESS says:
The lpValue parameter is a pointer to a handle to a process to use instead of the calling process as the parent for the process being created. The process to use must have the PROCESS_CREATE_PROCESS access right.
You said that you copied the other answer's code, but your code does not look like the other answer's code, and certainly does not contain the fix that the other answer had provided.
In your code, change this:
if (!UpdateProcThreadAttribute(..., hShellProcess, ...))
To this:
IntPtr lpValue = IntPtr.Zero;
...
lpValue = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.WriteIntPtr(lpValue, hShellProcess);
if (!UpdateProcThreadAttribute(..., lpValue, ...))
...
Marshal.FreeHGlobal(lpValue);
I have implemented all required code to get file type name from file path and it is working successfully but it returns subtracted type name e.g. if file path of .pdb or .pdf file then it will return "obe Acrobat Document" instead of "Adobe Acrobat Document"
I have used shell32.dll. I am not getting what happens please, help me to get rid out of it.
Source code:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
internal struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
internal class Win32
{
public const uint FILE_ATTRIBUTE_NORMAL = 0x80;
public const uint FILE_ATTRIBUTE_DIRECTORY = 0x10;
public const uint SHGFI_TYPENAME = 0x000000400;
public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010;
internal const uint SHGFI_SYSICONINDEX = 0x000004000;
internal const int ILD_TRANSPARENT = 0x1;
internal const uint SHGFI_ICON = 0x100;
internal const uint SHGFI_LARGEICON = 0x0;
internal const uint SHGFI_SMALLICON = 0x1;
[DllImport("shell32.dll", CharSet=CharSet.Unicode)]
internal static extern IntPtr SHGetFileInfo
(
string pszPath,
uint dwFileAttributes,
ref SHFILEINFO psfi,
uint cbSizeFileInfo,
uint uFlags
);
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
internal static extern int ExtractIconEx
(
string stExeFileName,
int nIconIndex,
ref IntPtr phiconLarge,
ref IntPtr phiconSmall,
int nIcons
);
[DllImport("comctl32.dll", SetLastError = true)]
internal static extern IntPtr ImageList_GetIcon
(
IntPtr himl,
int i,
int flags
);
[DllImport("user32.dll")]
internal static extern bool DestroyIcon(IntPtr hIcon);
}
internal static string GetFileType(string filename)
{
SHFILEINFO shinfo = new SHFILEINFO();
Win32.SHGetFileInfo
(
filename,
Win32.FILE_ATTRIBUTE_NORMAL,
ref shinfo, (uint)Marshal.SizeOf(shinfo),
Win32.SHGFI_TYPENAME |
Win32.SHGFI_USEFILEATTRIBUTES
);
return shinfo.szTypeName; //It return "obe Acrobat Document" Instead of "Adobe Acrobat Document"
}
The iIcon field in the C++ struct has type int.So, I just have to set the type of iIcon int only, not IntPtr. IntPtr works as per system platform so. I just set int type to iIcon like,
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
internal struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
And It's working fine...
I am trying to call a WinAPI function DeviceIoControl in C# with code IOCTL_DISK_SET_DISK_ATTRIBUTES and pass struct SET_DISK_ATTRIBUTES. I am trying do it with this code:
const uint GENERIC_READ = 0x80000000;
const uint GENERIC_WRITE = 0x40000000;
const int FILE_SHARE_READ = 0x1;
const int FILE_SHARE_WRITE = 0x2;
const uint IOCTL_DISK_SET_DISK_ATTRIBUTES = 0x0007c0f4;
const ulong DISK_ATTRIBUTE_READ_ONLY = 0x0000000000000002;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
IntPtr lpInBuffer,
uint nInBufferSize,
IntPtr lpOutBuffer,
uint nOutBufferSize,
out uint lpBytesReturned,
IntPtr lpOverlapped
);
struct SET_DISK_ATTRIBUTES
{
public uint Version;
public bool Persist;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public byte[] Reserved1;
public ulong Attributes;
public ulong AttributesMask;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public uint[] Reserved2;
};
private bool SetReadonly(IntPtr handle)
{
var sda = new SET_DISK_ATTRIBUTES();
sda.AttributesMask = DISK_ATTRIBUTE_READ_ONLY;
sda.Attributes = DISK_ATTRIBUTE_READ_ONLY;
int nPtrQryBytes = Marshal.SizeOf(sda);
sda.Version = (uint)nPtrQryBytes;
IntPtr ptrQuery = Marshal.AllocHGlobal(nPtrQryBytes);
Marshal.StructureToPtr(sda, ptrQuery, false);
uint byteReturned;
var res = DeviceIoControl(handle, IOCTL_DISK_SET_DISK_ATTRIBUTES, ptrQuery, (uint)nPtrQryBytes, IntPtr.Zero, 0, out byteReturned, IntPtr.Zero);
var ex = new Win32Exception(Marshal.GetLastWin32Error());
MessageBox.Show(ex.Message);
return res;
}
I receive error "Parameter incorrect". What is the right way to call DeviceIoControl function passing structure SET_DISK_ATTRIBUTES?
The original definition of SET_DISK_ATTRIBUTES:
typedef struct _SET_DISK_ATTRIBUTES {
DWORD Version;
BOOLEAN Persist;
BYTE Reserved1[3];
DWORDLONG Attributes;
DWORDLONG AttributesMask;
DWORD Reserved2[4];
} SET_DISK_ATTRIBUTES, *PSET_DISK_ATTRIBUTES;
makes use of BOOLEAN data type, which is defined as a synonym of unsigned char (1 byte), as opposed to BOOL that is a synonym of int (4 bytes).
C#'s bool is marshaled as BOOL by default.
You need to force it into one byte:
{
...
[MarshalAs(UnmanagedType.I1)]
public bool Persist;
...
}
Finally code to set disk readonly
const uint GENERIC_READ = 0x80000000;
const uint GENERIC_WRITE = 0x40000000;
const int FILE_SHARE_READ = 0x1;
const int FILE_SHARE_WRITE = 0x2;
const uint FILE_FLAG_WRITE_THROUGH = 0x80000000;
const uint FILE_FLAG_NO_BUFFERING = 0x20000000;
const uint IOCTL_DISK_SET_DISK_ATTRIBUTES = 0x0007c0f4;
const ulong DISK_ATTRIBUTE_READ_ONLY = 0x0000000000000002;
const uint IOCTL_DISK_UPDATE_PROPERTIES = 459072;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
IntPtr lpInBuffer,
uint nInBufferSize,
IntPtr lpOutBuffer,
uint nOutBufferSize,
out uint lpBytesReturned,
IntPtr lpOverlapped
);
struct SET_DISK_ATTRIBUTES
{
public uint Version;
[MarshalAs(UnmanagedType.I1)]
public bool Persist;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public byte[] Reserved1;
public ulong Attributes;
public ulong AttributesMask;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public uint[] Reserved2;
};
public IntPtr CreateHandle(string driveLetter)
{
string filename = #"\\.\" + driveLetter[0] + ":";
return CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, 0x3, FILE_FLAG_WRITE_THROUGH, IntPtr.Zero);
}
private void SetReadonly(IntPtr handle)
{
var sda = new SET_DISK_ATTRIBUTES();
sda.Persist = true;
sda.AttributesMask = DISK_ATTRIBUTE_READ_ONLY;
sda.Attributes = DISK_ATTRIBUTE_READ_ONLY;
sda.Reserved1 = new byte[3] { 0, 0, 0 };
sda.Reserved2 = new uint[4] { 0, 0, 0, 0 };
int nPtrQryBytes = Marshal.SizeOf(sda);
sda.Version = (uint)nPtrQryBytes;
IntPtr ptrQuery = Marshal.AllocHGlobal(nPtrQryBytes);
Marshal.StructureToPtr(sda, ptrQuery, false);
uint byteReturned;
bool res = DeviceIoControl(handle, IOCTL_DISK_SET_DISK_ATTRIBUTES, ptrQuery, (uint)nPtrQryBytes, IntPtr.Zero, 0, out byteReturned, IntPtr.Zero);
bool res2 = DeviceIoControl(handle, IOCTL_DISK_UPDATE_PROPERTIES, IntPtr.Zero, 0, IntPtr.Zero, 0, out byteReturned, IntPtr.Zero);
var mess = new List<string>();
mess.Add(new Win32Exception(Marshal.GetLastWin32Error()).Message);
mess.Add(new Win32Exception(Marshal.GetLastWin32Error()).Message);
MessageBox.Show(string.Join(" ", mess));
}
private void button1_Click(object sender, EventArgs e)
{
SetReadonly(CreateHandle(textBox1.Text));
}
For my program I need to get detailed information about the current displays. In my research I came across this post with talks about linking the System.Windows.Forms.Screen class and its EDID information. At first I tried copying and pasting the code found with using p/invoke to supply all the required native methods and structs, but it did not work and only gave me a string of ? for the InstanceID. So instead I tried to use the MSDN resources and again p/invoke to create the code myself. This is what I came up with:
private static void Foo()
{
Guid DisplayGUID = new Guid(Bar.GUID_DEVINTERFACE_MONITOR);
IntPtr DisplaysHandle = Bar.SetupDiGetClassDevs(ref DisplayGUID, null, IntPtr.Zero, (uint)(Win32.DIGCF_PRESENT | Win32.DIGCF_DEVICEINTERFACE));
Bar.SP_DEVICE_INTERFACE_DATA Data = new Bar.SP_DEVICE_INTERFACE_DATA();
Data.cbSize = Marshal.SizeOf(Data);
for (uint id = 0; Bar.SetupDiEnumDeviceInterfaces(DisplaysHandle, IntPtr.Zero, ref DisplayGUID, id, ref Data); id++)
{
Bar.SP_DEVINFO_DATA SPDID = new Bar.SP_DEVINFO_DATA();
SPDID.cbSize = (uint)Marshal.SizeOf(SPDID);
Bar.SP_DEVICE_INTERFACE_DETAIL_DATA NDIDD = new Bar.SP_DEVICE_INTERFACE_DETAIL_DATA();
if (IntPtr.Size == 8) //64 bit
NDIDD.cbSize = 8;
else //32 bit
NDIDD.cbSize = 4 + Marshal.SystemDefaultCharSize;
uint requiredsize = 0;
uint buffer = Bar.BUFFER_SIZE;
if (Bar.SetupDiGetDeviceInterfaceDetail(DisplaysHandle, ref Data, ref NDIDD, buffer, ref requiredsize, ref SPDID))
{
uint size = 0;
Bar.CM_Get_Device_ID_Size(out size, SPDID.DevInst);
IntPtr ptrInstanceBuf = Marshal.AllocHGlobal((int)size);
Bar.CM_Get_Device_ID(SPDID.DevInst, ref ptrInstanceBuf, size);
string InstanceID = Marshal.PtrToStringAuto(ptrInstanceBuf);
Console.WriteLine("InstanceID: {0}", InstanceID);
Marshal.FreeHGlobal(ptrInstanceBuf);
Console.WriteLine("DevicePath: {0}\n", NDIDD.DevicePath);
}
}
Bar.SetupDiDestroyDeviceInfoList(DisplaysHandle);
}
private class Bar
{
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, [MarshalAs(UnmanagedType.LPTStr)] string Enumerator, IntPtr hwndParent, uint Flags);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern bool SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport(#"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr hDevInfo, IntPtr devInfo, ref Guid interfaceClassGuid, UInt32 memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
[DllImport(#"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern Boolean SetupDiGetDeviceInterfaceDetail(IntPtr hDevInfo, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData, UInt32 deviceInterfaceDetailDataSize, ref UInt32 requiredSize, ref SP_DEVINFO_DATA deviceInfoData);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern int CM_Get_Device_ID_Size(out uint pulLen, UInt32 dnDevInst, int flags = 0);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern int CM_Get_Device_ID(uint dnDevInst, ref IntPtr Buffer, uint BufferLen, int ulFlags = 0);
public const int BUFFER_SIZE = 168; //guess
public const string GUID_DEVINTERFACE_MONITOR = "{E6F07B5F-EE97-4a90-B076-33F57BF4EAA7}";
[Flags]
public enum DiGetClassFlags : uint
{
DIGCF_DEFAULT = 0x00000001, // only valid with DIGCF_DEVICEINTERFACE
DIGCF_PRESENT = 0x00000002,
DIGCF_ALLCLASSES = 0x00000004,
DIGCF_PROFILE = 0x00000008,
DIGCF_DEVICEINTERFACE = 0x00000010,
}
[StructLayout(LayoutKind.Sequential)]
public struct SP_DEVICE_INTERFACE_DATA
{
public Int32 cbSize;
public Guid interfaceClassGuid;
public Int32 flags;
private UIntPtr reserved;
}
[StructLayout(LayoutKind.Sequential)]
public struct SP_DEVINFO_DATA
{
public uint cbSize;
public Guid classGuid;
public uint DevInst;
public IntPtr reserved;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SP_DEVICE_INTERFACE_DETAIL_DATA
{
public int cbSize;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = BUFFER_SIZE)]
public string DevicePath;
}
}
My code compiles and runs, but it does not give me the output I am looking for.
The output that I am looking for is:
InstanceID: DISPLAY\DELA00B\5&786e6ca&0&UID1048832
DevicePath: \\?\display#dela00b#5&786e6ca&0&uid1048832#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}
But this is the output I am receiving:
InstanceID: l
DevicePath: \\?\display#dela00b#5&786e6ca&0&uid1048832#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}
My question comes in the form of what is the problem causing the InstanceID to not output correctly.
Turns out I was using the wrong p/invoke signature. CM_Get_Device_ID should look like this:
[DllImport("setupapi.dll", SetLastError = true)]
public static extern int CM_Get_Device_ID(uint dnDevInst, StringBuilder Buffer, int BufferLen, int ulFlags = 0);
Also Updated Usage Code:
StringBuilder IDBuffer = new StringBuilder((int)buffer);
Bar.CM_Get_Device_ID(SPDID.DevInst, IDBuffer, (int)buffer);
Console.WriteLine("InstanceID: {0}", IDBuffer.ToString());
Console.WriteLine("DevicePath: {0}\n", NDIDD.DevicePath);
I really want to be able to do file redirection via shared pipes, and filter the list of inherited handles to only those stdout/stderr/stdin handles, and as far as I can find STARTUPINFOEX and extended attributes are the way to do that. I also need to be able to launch as a different user.
CreateProcess works for me when taking STARTUPINFOEX, and either passing no attributes, or a single attribute (either to change the parent, or filter the inherited handles).
CreateProcessWithLogonW works when taking STARTUPINFOEX, but only if I leave off EXTENDED_STARTUPINFO_PRESENT from the creation flags (basically treating STARTUPINFOEX as STARTUPINFO, even though startupinfo.cb is the full struct).
If I add EXTENDED_STARTUPINFO_PRESENT, I get the ever helpful "The parameter is incorrect", even without using any attributes (which works on CreateProcess)
The below works, until you uncomment // | NativeMethods.EXTENDED_STARTUPINFO_PRESENT,
public static void CreateProcessExtended(
string userName,
SecureString password)
{
var startupInfoEx = new NativeMethods.STARTUPINFOEX { StartupInfo = new NativeMethods.STARTUPINFO() };
startupInfoEx.StartupInfo.dwFlags = NativeMethods.STARTF_USESHOWWINDOW;
startupInfoEx.StartupInfo.wShowWindow = 0; // SW_HIDE
NativeMethods.PROCESS_INFORMATION processInfo;
startupInfoEx.StartupInfo.cb = Marshal.SizeOf(startupInfoEx);
IntPtr passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password);
bool retVal = NativeMethods.CreateProcessWithLogonW(
userName,
null,
passwordPtr,
NativeMethods.LogonFlags.LOGON_WITH_PROFILE,
null,
#"C:\windows\system32\notepad.exe",
(uint)NativeMethods.CREATE_NO_WINDOW | NativeMethods.CREATE_SUSPENDED,// | NativeMethods.EXTENDED_STARTUPINFO_PRESENT,
IntPtr.Zero,
null,
ref startupInfoEx,
out processInfo);
if (!retVal)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFOEX
{
public STARTUPINFO StartupInfo;
public IntPtr lpAttributeList;
}
[return: MarshalAs(UnmanagedType.Bool)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[DllImport("Advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
public static extern bool CreateProcessWithLogonW(
string userName,
string domain,
IntPtr password,
LogonFlags logonFlags,
string lpApplicationName,
string lpCommandLine,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
[In] ref STARTUPINFOEX lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
Edit.1
Sent in a filtered handle attribute list in case it was a contract difference that needed the extended attributes to be something other than IntPtr.Zero. Still failed. Again, worked in CreateProcess, failed in CreateProcessWithLogonW using these new sigs:
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UpdateProcThreadAttribute(
IntPtr lpAttributeList, uint dwFlags, uint Attribute, IntPtr lpValue,
IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool InitializeProcThreadAttributeList(
IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);