C# Correct managed code from C++ - c#

I have to use this external functions "GetOpenedFiles" (more info to: http://www.codeproject.com/KB/shell/OpenedFileFinder.aspx) into my C# application.
I don't know as I can write a wrapper of this function:
void GetOpenedFiles(LPCWSTR lpPath, OF_TYPE Filter, OF_CALLBACK CallBackProc, UINT_PTR pUserContext);
ORIGINAL C++ CODE (OpenFilefinder.h)
enum OF_TYPE
{
FILES_ONLY = 1,
MODULES_ONLY = 2,
ALL_TYPES = 3
};
struct OF_INFO_t
{
DWORD dwPID;
LPCWSTR lpFile;
HANDLE hFile;
};
typedef void (CALLBACK* OF_CALLBACK)(OF_INFO_t OpenedFileInf0, UINT_PTR uUserContext );
extern "C" __declspec(dllexport) void ShowOpenedFiles( LPCWSTR lpPath );
extern "C" __declspec(dllexport) void GetOpenedFiles( LPCWSTR lpPath,
OF_TYPE Filter,
OF_CALLBACK CallBackProc,
UINT_PTR pUserContext );
MY C# APPLICATION:
public enum OF_TYPE : int
{
FILES_ONLY = 1,
MODULES_ONLY = 2,
ALL_TYPES = 3
}
public struct OF_INFO_t
{
?????? dwPID;
?????? lpFile;
?????? hFile;
}
[DllImport("OpenFileFinder.dll", EntryPoint = "GetOpenedFiles")]
static extern void GetOpenedFiles(??????? lpPath, OF_TYPE filter, ????? CallBackProc, ????? pUserContext);
How can I use this dll function correctly in my C# app?
EDIT:
This is my latest snippet, but never invoke callback function:
namespace Open64
{
class Program
{
public Program()
{
GetOpenedFiles("C:\\", OF_TYPE.ALL_TYPES, CallbackFunction, UIntPtr.Zero);
}
//void GetOpenedFiles(LPCWSTR lpPath, OF_TYPE Filter, OF_CALLBACK CallBackProc, UINT_PTR pUserContext);
public enum OF_TYPE : int
{
FILES_ONLY = 1,
MODULES_ONLY = 2,
ALL_TYPES = 3
}
public struct OF_INFO_t
{
Int32 dwPID;
String lpFile;
IntPtr hFile;
}
public delegate void CallbackFunctionDef(OF_INFO_t info, IntPtr context);
[DllImport("OpenFileFinder.dll", EntryPoint = "GetOpenedFiles")]
static extern void GetOpenedFiles(string lpPath, OF_TYPE filter, CallbackFunctionDef CallBackProc, UIntPtr pUserContext);
public void CallbackFunction(OF_INFO_t info, IntPtr context)
{
Console.WriteLine("asd");
}
[STAThread]
static void Main()
{
new Program();
}
}
}

This is how you would marshal the following types:
DWORD => Int32
LPCWSTR => String
HANDLE => IntPtr
UINT_PTR => UIntPtr

public struct OF_INFO_t
{
Int32 dwPID;
String lpFile;
IntPtr hFile;
}
public delegate void CallbackFunctionDef(OF_INFO_t info, UIntPtr context);
[DllImport("OpenFileFinder.dll", EntryPoint = "GetOpenedFiles")]
static extern void GetOpenedFiles(string lpPath, OF_TYPE filter, CallbackFunctionDef CallBackProc, UIntPtr pUserContext);
EDIT: Here's the complete program
class Program
{
public Program()
{
GetOpenedFiles("C:\\", OF_TYPE.ALL_TYPES, CallbackFunction, UIntPtr.Zero);
Console.ReadKey();
}
//void GetOpenedFiles(LPCWSTR lpPath, OF_TYPE Filter, OF_CALLBACK CallBackProc, UINT_PTR pUserContext);
public enum OF_TYPE : int
{
FILES_ONLY = 1,
MODULES_ONLY = 2,
ALL_TYPES = 3
}
[StructLayout(LayoutKind.Sequential,CharSet = CharSet.Unicode)]
public struct OF_INFO_t
{
public Int32 dwPID;
public String lpFile;
public IntPtr hFile;
}
public delegate void CallbackFunctionDef(OF_INFO_t info, IntPtr context);
[DllImport("OpenFileFinder.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, EntryPoint = "GetOpenedFiles")]
static extern void GetOpenedFiles(string lpPath, OF_TYPE filter, CallbackFunctionDef CallBackProc, UIntPtr pUserContext);
public void CallbackFunction(OF_INFO_t info, IntPtr context)
{
//List the files
Console.WriteLine(info.lpFile);
}
[STAThread]
static void Main()
{
new Program();
}
}

Related

WaitForDebugEvent (kernel32.dll) bug or what?

i'm new and i need your help resolving this issue.
I'm trying to create a simple debugger to understand how debuggers works and how is loaded exes in memory. I have already written the code which works as well, but now there is the problem: when i try to call WaitForDebugEvent (a kernel32 function) to get the debug event it works, in fact the debug_event variable is written, but this function clears all the variables in my application. So it clear also:
this (current form)
EventArgs (arguments of my form load function)
object sender (the object who called the function)
So i can't continue executing my app because all the vars were deleted. I wouldn't think this is a kernel32 or a Visual Studio bug...
This is the code:
(Structs and imports got from pInvoke.net and MSDN)
[DllImport("kernel32.dll")]
static extern bool DebugActiveProcess(uint dwProcessId);
[DllImport("kernel32.dll", EntryPoint = "WaitForDebugEvent")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WaitForDebugEvent([In] ref DEBUG_EVENT lpDebugEvent, uint dwMilliseconds);
[DllImport("kernel32.dll")]
static extern bool ContinueDebugEvent(uint dwProcessId, uint dwThreadId, uint dwContinueStatus);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DebugActiveProcessStop([In] int Pid);
public struct DEBUG_EVENT
{
public int dwDebugEventCode;
public int dwProcessId;
public int dwThreadId;
public struct u
{
public EXCEPTION_DEBUG_INFO Exception;
public CREATE_THREAD_DEBUG_INFO CreateThread;
public CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
public EXIT_THREAD_DEBUG_INFO ExitThread;
public EXIT_PROCESS_DEBUG_INFO ExitProcess;
public LOAD_DLL_DEBUG_INFO LoadDll;
public UNLOAD_DLL_DEBUG_INFO UnloadDll;
public OUTPUT_DEBUG_STRING_INFO DebugString;
public RIP_INFO RipInfo;
};
};
[StructLayout(LayoutKind.Sequential)]
public struct EXCEPTION_DEBUG_INFO
{
public EXCEPTION_RECORD ExceptionRecord;
public uint dwFirstChance;
}
[StructLayout(LayoutKind.Sequential)]
public struct EXCEPTION_RECORD
{
public uint ExceptionCode;
public uint ExceptionFlags;
public IntPtr ExceptionRecord;
public IntPtr ExceptionAddress;
public uint NumberParameters;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 15, ArraySubType = UnmanagedType.U4)]
public uint[] ExceptionInformation;
}
public delegate uint PTHREAD_START_ROUTINE(IntPtr lpThreadParameter);
[StructLayout(LayoutKind.Sequential)]
public struct CREATE_THREAD_DEBUG_INFO
{
public IntPtr hThread;
public IntPtr lpThreadLocalBase;
public PTHREAD_START_ROUTINE lpStartAddress;
}
//public delegate uint PTHREAD_START_ROUTINE(IntPtr lpThreadParameter);
[StructLayout(LayoutKind.Sequential)]
public struct CREATE_PROCESS_DEBUG_INFO
{
public IntPtr hFile;
public IntPtr hProcess;
public IntPtr hThread;
public IntPtr lpBaseOfImage;
public uint dwDebugInfoFileOffset;
public uint nDebugInfoSize;
public IntPtr lpThreadLocalBase;
public PTHREAD_START_ROUTINE lpStartAddress;
public IntPtr lpImageName;
public ushort fUnicode;
}
[StructLayout(LayoutKind.Sequential)]
public struct EXIT_THREAD_DEBUG_INFO
{
public uint dwExitCode;
}
[StructLayout(LayoutKind.Sequential)]
public struct EXIT_PROCESS_DEBUG_INFO
{
public uint dwExitCode;
}
[StructLayout(LayoutKind.Sequential)]
public struct LOAD_DLL_DEBUG_INFO
{
public IntPtr hFile;
public IntPtr lpBaseOfDll;
public uint dwDebugInfoFileOffset;
public uint nDebugInfoSize;
public IntPtr lpImageName;
public ushort fUnicode;
}
[StructLayout(LayoutKind.Sequential)]
public struct UNLOAD_DLL_DEBUG_INFO
{
public IntPtr lpBaseOfDll;
}
[StructLayout(LayoutKind.Sequential)]
public struct OUTPUT_DEBUG_STRING_INFO
{
[MarshalAs(UnmanagedType.LPStr)]
public string lpDebugStringData;
public ushort fUnicode;
public ushort nDebugStringLength;
}
[StructLayout(LayoutKind.Sequential)]
public struct RIP_INFO
{
public uint dwError;
public uint dwType;
}
And the main loop of debugger:
private void Form1_Load(object sender, EventArgs e)
{
DebugActiveProcess((uint)Process.GetProcessesByName("notepad")[0].Id);
DEBUG_EVENT debug_event = new DEBUG_EVENT();
CONTEXT context = new CONTEXT();
context.ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL;
while (true)
{
unchecked
{
if (WaitForDebugEvent(ref debug_event, (uint)double.PositiveInfinity))
{
...
ContinueDebugEvent((uint)debug_event.dwProcessId, (uint)debug_event.dwThreadId, (uint)0x10002);
}
}
}
}
What can i do? Thanks in advance...
EDIT:
I have rewritten the code in C++ to see if the problem there was there too. But there was no issue... so i think the problem lays only in C#. This is the code in C++:
IMPORTS:
#include <windows.h>
#include <tlhelp32.h>
#include <msclr\marshal_cppstd.h>
CODE:
private: System::Void DebuggerForm_Load(System::Object^ sender, System::EventArgs^ e) {
std::wstring processName = msclr::interop::marshal_as<std::wstring, String^>("myExe.exe");
DWORD id = getProcessId(processName);
if (id == 0) std::exit(0);
DebugActiveProcess(id);
DEBUG_EVENT debug_event = { 0 };
while (true)
{
if (WaitForDebugEvent(&debug_event, INFINITE)) {
// TODO
ContinueDebugEvent(debug_event.dwProcessId, debug_event.dwThreadId, DBG_CONTINUE);
}
}
}
DWORD getProcessId(const std::wstring& processName)
{
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE)
return 0;
Process32First(processesSnapshot, &processInfo);
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
while (Process32Next(processesSnapshot, &processInfo))
{
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processesSnapshot);
return 0;
}
First of all, You should enable the SE_DEBUG_NAME privilege on the targeted process:
(SE_DEBUG_NAME = "SeDebugPrivilege")
Use OpenProcessToken with TOKEN_ADJUST_PRIVILEGES and TOKEN_QUERY access flags.
Use LookupPrivilegeValue to retrieve the LUID of the SE_DEBUG_NAME privilege name.
Use AdjustTokenPrivileges to enable the SE_DEBUG_NAME privilege.
CloseHandle
For the 3rd step you need a TOKEN_PRIVILEGES structure, where the PrivilegesCount field must set to 1. Also You must set the first(zero index) item of the Privilege field (Luid: see 2nd step, Attributes: SE_PRIVILEGE_ENABLED)
The DEBUG_EVENT structure:
The u field of the structure is an union, it means that it only contains one of the listed structs. Try to use LayoutKind.Explicit and decorate every field with the attribute FieldOffset to define the correct offset inside the structure. Try this:
[StructLayout(LayoutKind.Explicit)]
public struct DEBUG_EVENT
{
[FieldOffset(0)]
public int dwDebugEventCode;
[FieldOffset(4)]
public int dwProcessId;
[FieldOffset(8)]
public int dwThreadId;
[FieldOffset(12)]
[StructLayout(LayoutKind.Explicit)]
public struct u {
[FieldOffset(0)]
public EXCEPTION_DEBUG_INFO Exception;
[FieldOffset(0)]
public CREATE_THREAD_DEBUG_INFO CreateThread;
[FieldOffset(0)]
public CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
[FieldOffset(0)]
public EXIT_THREAD_DEBUG_INFO ExitThread;
[FieldOffset(0)]
public EXIT_PROCESS_DEBUG_INFO ExitProcess;
[FieldOffset(0)]
public LOAD_DLL_DEBUG_INFO LoadDll;
[FieldOffset(0)]
public UNLOAD_DLL_DEBUG_INFO UnloadDll;
[FieldOffset(0)]
public OUTPUT_DEBUG_STRING_INFO DebugString;
[FieldOffset(0)]
public RIP_INFO RipInfo;
}
};

Drag & drop from Windows Portable Device to WPF Application

I'm working on a WPF app which allows user to drag and drop files from Windows Explorer. For normal files, I'm able to access the path using
string[] fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
But for WPD files, its returning null. Have tried to follow the solution given in http://us.generation-nt.com/answer/drag-drop-pictures-wpd-camera-help-31497882.html#r , but i couldn't make it work. I'm getting AccessVoilationException when trying to get the count of items from the Shell array. I have posted the question in MSDN(http://social.msdn.microsoft.com/Forums/vstudio/en-US/ef7fc152-dd1b-4774-adb7-47b48726daea/drag-drop-from-windows-portable-device-to-wpf-application?forum=wpf), but didn't get any leads.
Is there something that I'm missing here? Could you please help me solve this issue?
Following is the relevant part my code.
public enum SIGDN : uint
{
NORMALDISPLAY = 0,
PARENTRELATIVEPARSING = 0x80018001,
PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
DESKTOPABSOLUTEPARSING = 0x80028000,
PARENTRELATIVEEDITING = 0x80031001,
DESKTOPABSOLUTEEDITING = 0x8004c000,
FILESYSPATH = 0x80058000,
URL = 0x80068000
}
internal class IIDGuid
{
private IIDGuid() { } // Avoid FxCop violation AvoidUninstantiatedInternalClasses
// IID GUID strings for relevant COM interfaces
internal const string IModalWindow = "b4db1657-70d7-485e-8e3e-6fcb5a5c1802";
internal const string IFileDialog = "42f85136-db7e-439c-85f1-e4075d135fc8";
internal const string IFileOpenDialog = "d57c7288-d4ad-4768-be02-9d969532d960";
internal const string IFileSaveDialog = "84bccd23-5fde-4cdb-aea4-af64b83d78ab";
internal const string IFileDialogEvents = "973510DB-7D7F-452B-8975-74A85828D354";
internal const string IShellItem = "43826D1E-E718-42EE-BC55-A1E261C37BFE";
internal const string IShellItemArray = "B63EA76D-1F85-456F-A19C-48159EFA858B";
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
public interface IShellItem
{
void BindToHandler(IntPtr pbc,
[MarshalAs(UnmanagedType.LPStruct)]Guid bhid,
[MarshalAs(UnmanagedType.LPStruct)]Guid riid,
out IntPtr ppv);
void GetParent(out IShellItem ppsi);
void GetDisplayName(SIGDN sigdnName, out IntPtr ppszName);
void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
void Compare(IShellItem psi, uint hint, out int piOrder);
};
[ComImport]
[Guid(IIDGuid.IShellItemArray)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IShellItemArray
{
// Not supported: IBindCtx
void BindToHandler([In, MarshalAs(UnmanagedType.Interface)] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, out IntPtr ppvOut);
void GetPropertyStore([In] int Flags, [In] ref Guid riid, out IntPtr ppv);
void GetCount(out uint pdwNumItems);
void GetItemAt([In] uint dwIndex, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
void EnumItems([MarshalAs(UnmanagedType.Interface)] out IntPtr ppenumShellItems);
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern int SHCreateShellItemArrayFromDataObject(
System.Runtime.InteropServices.ComTypes.IDataObject pdo,
ref Guid riid,
[MarshalAs(UnmanagedType.Interface)] out IShellItemArray ppv);
[DllImport("kernel32.dll", SetLastError = true)]
static extern Int32 GetLastError();
private void OnFileDrop(object sender, DragEventArgs e)
{
string[] fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, false);// null
System.Runtime.InteropServices.ComTypes.IDataObject mydata = e.Data as System.Runtime.InteropServices.ComTypes.IDataObject;
IShellItemArray nativeShellItemArray;
Guid guid = new Guid(IIDGuid.IShellItemArray);
int retCode = SHCreateShellItemArrayFromDataObject(mydata, ref guid, out nativeShellItemArray);
IShellItem nativeShellItem;
if (retCode == 0)
{
IntPtr displayname;
uint items = 0;
try
{
nativeShellItemArray.GetCount(out items); //Getting AccessVoilationException in this line
}
catch (Exception ex)
{
}
if (items > 0)
{
for (uint item = 0; item < items; item++)
{
nativeShellItemArray.GetItemAt(item, out nativeShellItem);
nativeShellItem.GetDisplayName(SIGDN.DESKTOPABSOLUTEPARSING, out displayname);
//Do something
}
}
}
}

How to use SetupIterateCabinet with C#

I am attempting to write code to extract the contents of a CAB file, however I am having trouble using the SetupIterateCabinet routine.
Please see doc here http://msdn.microsoft.com/en-us/library/aa377404(v=vs.85).aspx
I can import it properly like this
private const uint SPFILENOTIFY_CABINETINFO = 0x00000010;
private const uint SPFILENOTIFY_FILEINCABINET = 0x00000011;
private const uint SPFILENOTIFY_NEEDNEWCABINET = 0x00000012;
private const uint SPFILENOTIFY_FILEEXTRACTED = 0x00000013;
private const uint SPFILENOTIFY_FILEOPDELAYED = 0x00000014;
private const uint NO_ERROR = 0;
private const uint FILEOP_ABORT = 0;
private const uint FILEOP_DOIT= 1;
private const uint FILEOP_SKIP= 2;
private const uint FILEOP_NEWPATH= 4;
static void Main(string[] args)
{
SetupIterateCabinet("c:\\SomeCab.cab", 0, new PSP_FILE_CALLBACK(CallBack), 0);
Console.ReadKey();
}
[DllImport("SetupApi.dll", CharSet = CharSet.Auto)]
public static extern bool SetupIterateCabinet(string cabinetFile,
uint reserved, PSP_FILE_CALLBACK callBack, uint context);
public delegate uint PSP_FILE_CALLBACK(uint context, uint notification,
IntPtr param1, IntPtr param2);
private static uint CallBack(uint context, uint notification, IntPtr param1,
IntPtr param2)
{
uint rtnValue = NO_ERROR;
switch (notification)
{
case SPFILENOTIFY_FILEINCABINET:
rtnValue = OnFileFound(context, notification, param1, param2);
break;
case SPFILENOTIFY_FILEEXTRACTED:
rtnValue = OnFileExtractComplete(param1);
break;
case SPFILENOTIFY_NEEDNEWCABINET:
rtnValue = NO_ERROR;
break;
}
return rtnValue;
}
private static uint OnFileExtractComplete(IntPtr param1)
{
Console.WriteLine("Complete");
return FILEOP_DOIT;
}
[StructLayout(LayoutKind.Sequential)]
struct _FILE_IN_CABINET_INFO {
IntPtr NameInCabinet;
int FileSize;
int Win32Error;
int DosDate;
int DosTime;
int DosAttribs;
StringBuilder FullTargetName;
};
static private uint OnFileFound(uint context, uint notification, IntPtr param1, IntPtr param2)
{
_FILE_IN_CABINET_INFO fc = new _FILE_IN_CABINET_INFO() ;
Marshal.PtrToStructure(param1, fc);
return 1;
}
However the problem comes when attempting to process the SPFILENOTIFY_FILEINCABINET event in the callback. According to the documentation this is a struct, that I need to put the name of where I want to have the file extracted to in. I am having trouble figuring out what the struct should look like and maybe how to convert the param to a struct.
I think you have a problem with the return values of your callback function. On SPFILENOTIFY_FILECABINET, you should be returning FILEOP_DOIT. Before returning you should be setting up the filename in the FILE_IN_CABINTE_INFO. Please check the codeproject post http://www.codeproject.com/Articles/7165/Iterate-and-Extract-Cabinet-File
I might add some code sample later. GTG now
EDIT:
Code sample below. I haven't tried it, but I believe it should work. I have tried to keep the structure similar to your code. This should show you how to define the FILE_IN_CABINET_INFO class and the correct values to be set and returned in the callback
public delegate uint PSP_FILE_CALLBACK(uint context, uint notification, IntPtr param1, IntPtr param2);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class FILE_IN_CABINET_INFO {
public String NameInCabinet;
public uint FileSize;
public uint Win32Error;
public ushort DosDate;
public ushort DosTime;
public ushort DosAttribs;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public System.String FullTargetName;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class FILEPATHS {
public String Target;
public String Source;
public uint Win32Error;
public uint Flags;
}
public const uint SPFILENOTIFY_FILEINCABINET = 0x00000011; // The file has been extracted from the cabinet.
public const uint SPFILENOTIFY_NEEDNEWCABINET = 0x00000012; // file is encountered in the cabinet.
public const uint SPFILENOTIFY_FILEEXTRACTED = 0x00000013; // The current file is continued in the next cabinet.
public const uint NO_ERROR = 0;
public const uint FILEOP_ABORT = 0; // Abort cabinet processing.
public const uint FILEOP_DOIT = 1; // Extract the current file.
public const uint FILEOP_SKIP = 2; // Skip the current file.
[DllImport("SetupApi.dll", CharSet = CharSet.Auto)]
public static extern bool SetupIterateCabinet(string cabinetFile, uint reserved, PSP_FILE_CALLBACK callBack, uint context);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern uint GetLastError();
static void Main(string[] args) {
IterateCabinet(#"c:\SomeCab.cab");
}
public static void IterateCabinet(string filePath) {
PSP_FILE_CALLBACK callback = new PSP_FILE_CALLBACK(CallBack);
if (!SetupIterateCabinet(filePath, 0, callback, 0))
throw new Win32Exception((int)GetLastError());
}
static uint CallBack(uint context, uint notification, IntPtr param1, IntPtr param2) {
if (notification == SPFILENOTIFY_FILEINCABINET)
return OnFileFound(context, notification, param1, param2);
else if (notification == SPFILENOTIFY_FILEEXTRACTED)
return OnFileExtractComplete(param1);
else if (notification == SPFILENOTIFY_NEEDNEWCABINET)
return NO_ERROR;
return NO_ERROR;
}
static uint OnFileFound(uint context, uint notification, IntPtr param1, IntPtr param2) {
FILE_IN_CABINET_INFO fileInCabinetInfo = (FILE_IN_CABINET_INFO)Marshal.PtrToStructure(param1, typeof(FILE_IN_CABINET_INFO));
fileInCabinetInfo.FullTargetName = fileInCabinetInfo.NameInCabinet; // extract to current directory
return FILEOP_DOIT;
}
static uint OnFileExtractComplete(IntPtr param1) {
FILEPATHS filePaths = (FILEPATHS)Marshal.PtrToStructure(param1, typeof(FILEPATHS));
if (filePaths.Win32Error == NO_ERROR)
Console.WriteLine("File {0} extracted to {1} " + filePaths.Source, filePaths.Target);
else
Console.WriteLine("Errors occurred while extracting cab File {0} to {1} ", filePaths.Source, filePaths.Target);
return filePaths.Win32Error;
}

How can I manipulate token privileges in .Net?

I'd like to use C# to determine which privileges are assigned to my process/thread token, and adjust them as necessary. For example, in order for my program to restart the computer, it must first enable the SeShutdownPrivilege privilege.
How can that be done safely from managed code?
This turns out to be non-trivial because there's no built-in mechanism for it. Not only is P/Invoke required, but you must code carefully to make sure that you don't "leak" privileges by enabling them and then not disabling them soon enough (though not an issue if you're restarting the computer).
For a complete code sample with description, read the MSDN magazine article from March 2005 "Manipulate Privileges in Managed Code Reliably, Securely, and Efficiently" by Mark Novak.
Here's the P/Invoke declarations:
using System;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
namespace PrivilegeClass
{
[Flags]
internal enum TokenAccessLevels
{
AssignPrimary = 0x00000001,
Duplicate = 0x00000002,
Impersonate = 0x00000004,
Query = 0x00000008,
QuerySource = 0x00000010,
AdjustPrivileges = 0x00000020,
AdjustGroups = 0x00000040,
AdjustDefault = 0x00000080,
AdjustSessionId = 0x00000100,
Read = 0x00020000 | Query,
Write = 0x00020000 | AdjustPrivileges | AdjustGroups | AdjustDefault,
AllAccess = 0x000F0000 |
AssignPrimary |
Duplicate |
Impersonate |
Query |
QuerySource |
AdjustPrivileges |
AdjustGroups |
AdjustDefault |
AdjustSessionId,
MaximumAllowed = 0x02000000
}
internal enum SecurityImpersonationLevel
{
Anonymous = 0,
Identification = 1,
Impersonation = 2,
Delegation = 3,
}
internal enum TokenType
{
Primary = 1,
Impersonation = 2,
}
internal sealed class NativeMethods
{
internal const uint SE_PRIVILEGE_DISABLED = 0x00000000;
internal const uint SE_PRIVILEGE_ENABLED = 0x00000002;
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct LUID
{
internal uint LowPart;
internal uint HighPart;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct LUID_AND_ATTRIBUTES
{
internal LUID Luid;
internal uint Attributes;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct TOKEN_PRIVILEGE
{
internal uint PrivilegeCount;
internal LUID_AND_ATTRIBUTES Privilege;
}
internal const string ADVAPI32 = "advapi32.dll";
internal const string KERNEL32 = "kernel32.dll";
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_NO_TOKEN = 0x3f0;
internal const int ERROR_NOT_ALL_ASSIGNED = 0x514;
internal const int ERROR_NO_SUCH_PRIVILEGE = 0x521;
internal const int ERROR_CANT_OPEN_ANONYMOUS = 0x543;
[DllImport(
KERNEL32,
SetLastError=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern bool CloseHandle(IntPtr handle);
[DllImport(
ADVAPI32,
CharSet=CharSet.Unicode,
SetLastError=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern bool AdjustTokenPrivileges (
[In] SafeTokenHandle TokenHandle,
[In] bool DisableAllPrivileges,
[In] ref TOKEN_PRIVILEGE NewState,
[In] uint BufferLength,
[In,Out] ref TOKEN_PRIVILEGE PreviousState,
[In,Out] ref uint ReturnLength);
[DllImport(
ADVAPI32,
CharSet=CharSet.Auto,
SetLastError=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern
bool RevertToSelf();
[DllImport(
ADVAPI32,
EntryPoint="LookupPrivilegeValueW",
CharSet=CharSet.Auto,
SetLastError=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern
bool LookupPrivilegeValue (
[In] string lpSystemName,
[In] string lpName,
[In,Out] ref LUID Luid);
[DllImport(
KERNEL32,
CharSet=CharSet.Auto,
SetLastError=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern
IntPtr GetCurrentProcess();
[DllImport(
KERNEL32,
CharSet=CharSet.Auto,
SetLastError=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern
IntPtr GetCurrentThread ();
[DllImport(
ADVAPI32,
CharSet=CharSet.Unicode,
SetLastError=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern
bool OpenProcessToken (
[In] IntPtr ProcessToken,
[In] TokenAccessLevels DesiredAccess,
[In,Out] ref SafeTokenHandle TokenHandle);
[DllImport
(ADVAPI32,
CharSet=CharSet.Unicode,
SetLastError=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern
bool OpenThreadToken(
[In] IntPtr ThreadToken,
[In] TokenAccessLevels DesiredAccess,
[In] bool OpenAsSelf,
[In,Out] ref SafeTokenHandle TokenHandle);
[DllImport
(ADVAPI32,
CharSet=CharSet.Unicode,
SetLastError=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern
bool DuplicateTokenEx(
[In] SafeTokenHandle ExistingToken,
[In] TokenAccessLevels DesiredAccess,
[In] IntPtr TokenAttributes,
[In] SecurityImpersonationLevel ImpersonationLevel,
[In] TokenType TokenType,
[In,Out] ref SafeTokenHandle NewToken);
[DllImport
(ADVAPI32,
CharSet=CharSet.Unicode,
SetLastError=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern
bool SetThreadToken(
[In] IntPtr Thread,
[In] SafeTokenHandle Token);
static NativeMethods()
{
}
}
}
Here's what I use. It is based off of the Mark Novak article, but with less paranoia for untrusted stack frames, CER's, or reentrance (since I assume you are not writing internet explorer or a SQL Server Add-in).
Privilege.cs:
using System;
using Microsoft.Win32.SafeHandles;
using System.Collections.Specialized;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Threading;
using Luid = Esatto.Win32.Processes.NativeMethods.LUID;
using Win32Exception = System.ComponentModel.Win32Exception;
using PrivilegeNotHeldException = System.Security.AccessControl.PrivilegeNotHeldException;
using static Esatto.Win32.Processes.NativeMethods;
using System.Linq;
using System.Security.Principal;
// http://msdn.microsoft.com/en-us/magazine/cc163823.aspx
namespace Esatto.Win32.Processes
{
public static class Privilege
{
#region Privilege names
public const string
CreateToken = "SeCreateTokenPrivilege",
AssignPrimaryToken = "SeAssignPrimaryTokenPrivilege",
LockMemory = "SeLockMemoryPrivilege",
IncreaseQuota = "SeIncreaseQuotaPrivilege",
UnsolicitedInput = "SeUnsolicitedInputPrivilege",
MachineAccount = "SeMachineAccountPrivilege",
TrustedComputingBase = "SeTcbPrivilege",
Security = "SeSecurityPrivilege",
TakeOwnership = "SeTakeOwnershipPrivilege",
LoadDriver = "SeLoadDriverPrivilege",
SystemProfile = "SeSystemProfilePrivilege",
SystemTime = "SeSystemtimePrivilege",
ProfileSingleProcess = "SeProfileSingleProcessPrivilege",
IncreaseBasePriority = "SeIncreaseBasePriorityPrivilege",
CreatePageFile = "SeCreatePagefilePrivilege",
CreatePermanent = "SeCreatePermanentPrivilege",
Backup = "SeBackupPrivilege",
Restore = "SeRestorePrivilege",
Shutdown = "SeShutdownPrivilege",
Debug = "SeDebugPrivilege",
Audit = "SeAuditPrivilege",
SystemEnvironment = "SeSystemEnvironmentPrivilege",
ChangeNotify = "SeChangeNotifyPrivilege",
RemoteShutdown = "SeRemoteShutdownPrivilege",
Undock = "SeUndockPrivilege",
SyncAgent = "SeSyncAgentPrivilege",
EnableDelegation = "SeEnableDelegationPrivilege",
ManageVolume = "SeManageVolumePrivilege",
Impersonate = "SeImpersonatePrivilege",
CreateGlobal = "SeCreateGlobalPrivilege",
TrustedCredentialManagerAccess = "SeTrustedCredManAccessPrivilege",
ReserveProcessor = "SeReserveProcessorPrivilege";
#endregion
public static void RunWithPrivileges(Action action, params string[] privs)
{
if (privs == null || privs.Length == 0)
{
throw new ArgumentNullException(nameof(privs));
}
var luids = privs
.Select(e => new LUID_AND_ATTRIBUTES { Luid = GetLuidForName(e), Attributes = SE_PRIVILEGE_ENABLED })
.ToArray();
RuntimeHelpers.PrepareConstrainedRegions();
try { /* CER */ }
finally
{
using (var threadToken = new ThreadTokenScope())
using (new ThreadPrivilegeScope(threadToken, luids))
{
action();
}
}
}
private static LUID_AND_ATTRIBUTES[] AdjustTokenPrivileges2(SafeTokenHandle token, LUID_AND_ATTRIBUTES[] attrs)
{
var sizeofAttr = Marshal.SizeOf<LUID_AND_ATTRIBUTES>();
var pDesired = Marshal.AllocHGlobal(4 /* count */ + attrs.Length * sizeofAttr);
try
{
// Fill pStruct
{
Marshal.WriteInt32(pDesired, attrs.Length);
var pAttr = pDesired + 4;
for (int i = 0; i < attrs.Length; i++)
{
Marshal.StructureToPtr(attrs[i], pAttr, false);
pAttr += sizeofAttr;
}
}
// Call Adjust
const int cbPrevious = 16384 /* some arbitrarily high number */;
var pPrevious = Marshal.AllocHGlobal(cbPrevious);
try
{
if (!AdjustTokenPrivileges(token, false, pDesired, cbPrevious, pPrevious, out var retLen))
{
throw new Win32Exception();
}
// Parse result
{
var result = new LUID_AND_ATTRIBUTES[Marshal.ReadInt32(pPrevious)];
var pAttr = pPrevious + 4;
for (int i = 0; i < result.Length; i++)
{
result[i] = Marshal.PtrToStructure<LUID_AND_ATTRIBUTES>(pAttr);
}
return result;
}
}
finally { Marshal.FreeHGlobal(pPrevious); }
}
finally { Marshal.FreeHGlobal(pDesired); }
}
private static Luid GetLuidForName(string priv)
{
if (!LookupPrivilegeValue(null, priv, out var result))
{
throw new Win32Exception();
}
return result;
}
private class ThreadPrivilegeScope : IDisposable
{
private LUID_AND_ATTRIBUTES[] RevertTo;
private Thread OwnerThread;
private readonly ThreadTokenScope Token;
public ThreadPrivilegeScope(ThreadTokenScope token, LUID_AND_ATTRIBUTES[] setTo)
{
this.OwnerThread = Thread.CurrentThread;
this.Token = token ?? throw new ArgumentNullException(nameof(token));
this.RevertTo = AdjustTokenPrivileges2(token.Handle, setTo);
}
public void Dispose()
{
if (OwnerThread != Thread.CurrentThread)
{
throw new InvalidOperationException("Wrong thread");
}
if (RevertTo == null)
{
return;
}
AdjustTokenPrivileges2(Token.Handle, RevertTo);
}
}
private class ThreadTokenScope : IDisposable
{
private bool IsImpersonating;
private readonly Thread OwnerThread;
public readonly SafeTokenHandle Handle;
[ThreadStatic]
private static ThreadTokenScope Current;
public ThreadTokenScope()
{
if (Current != null)
{
throw new InvalidOperationException("Reentrance to ThreadTokenScope");
}
this.OwnerThread = Thread.CurrentThread;
if (!OpenThreadToken(GetCurrentThread(), TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges, true, out var token))
{
var error = Marshal.GetLastWin32Error();
if (error != ERROR_NO_TOKEN)
{
throw new Win32Exception(error);
}
// No token is on the thread, copy from process
if (!OpenProcessToken(GetCurrentProcess(), TokenAccessLevels.Duplicate, out var processToken))
{
throw new Win32Exception();
}
if (!DuplicateTokenEx(processToken, TokenAccessLevels.Impersonate | TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
IntPtr.Zero, SecurityImpersonationLevel.Impersonation, TokenType.Impersonation, out token))
{
throw new Win32Exception();
}
if (!SetThreadToken(IntPtr.Zero, token))
{
throw new Win32Exception();
}
this.IsImpersonating = true;
}
this.Handle = token;
Current = this;
}
public void Dispose()
{
if (OwnerThread != Thread.CurrentThread)
{
throw new InvalidOperationException("Wrong thread");
}
if (Current != this)
{
throw new ObjectDisposedException(nameof(ThreadTokenScope));
}
Current = null;
if (IsImpersonating)
{
RevertToSelf();
}
IsImpersonating = false;
}
}
}
}
NativeMethods.cs:
using Microsoft.Win32.SafeHandles;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
namespace Esatto.Win32.Processes
{
internal static class NativeMethods
{
const string Advapi32 = "advapi32.dll";
const string Kernel32 = "kernel32.dll";
const string Wtsapi32 = "wtsapi32.dll";
const string Userenv = "userenv.dll";
#region constants
public const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
public const uint SE_PRIVILEGE_DISABLED = 0x00000000;
public const uint SE_PRIVILEGE_ENABLED = 0x00000002;
public const int ERROR_SUCCESS = 0x0;
public const int ERROR_ACCESS_DENIED = 0x5;
public const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
public const int ERROR_NO_TOKEN = 0x3f0;
public const int ERROR_NOT_ALL_ASSIGNED = 0x514;
public const int ERROR_NO_SUCH_PRIVILEGE = 0x521;
public const int ERROR_CANT_OPEN_ANONYMOUS = 0x543;
public const uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
public const uint STANDARD_RIGHTS_READ = 0x00020000;
public const uint NORMAL_PRIORITY_CLASS = 0x0020;
public const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
public const uint MAX_PATH = 260;
public const uint CREATE_NO_WINDOW = 0x08000000;
public const uint INFINITE = 0xFFFFFFFF;
#endregion
#region Advapi32
[DllImport(Advapi32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern bool AdjustTokenPrivileges(SafeTokenHandle TokenHandle, bool DisableAllPrivileges,
IntPtr NewState, uint BufferLength, IntPtr PreviousState, out uint ReturnLength);
[DllImport(Advapi32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern bool RevertToSelf();
[DllImport(Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID Luid);
[DllImport(Advapi32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern bool OpenProcessToken(IntPtr ProcessToken, TokenAccessLevels DesiredAccess, out SafeTokenHandle TokenHandle);
[DllImport(Advapi32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern bool OpenThreadToken(IntPtr ThreadToken, TokenAccessLevels DesiredAccess, bool OpenAsSelf, out SafeTokenHandle TokenHandle);
[DllImport(Advapi32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern bool DuplicateTokenEx(SafeTokenHandle ExistingToken, TokenAccessLevels DesiredAccess,
IntPtr TokenAttributes, SecurityImpersonationLevel ImpersonationLevel, TokenType TokenType, out SafeTokenHandle NewToken);
[DllImport(Advapi32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern bool SetThreadToken(IntPtr Thread, SafeTokenHandle Token);
[DllImport(Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CreateProcessAsUser(SafeTokenHandle hToken,
StringBuilder appExeName, StringBuilder commandLine, IntPtr processAttributes,
IntPtr threadAttributes, bool inheritHandles, uint dwCreationFlags,
EnvironmentBlockSafeHandle environment, string currentDirectory, ref STARTUPINFO startupInfo,
out PROCESS_INFORMATION startupInformation);
[DllImport(Advapi32, CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool GetTokenInformation(IntPtr TokenHandle,
TokenInformationClass TokenInformationClass, out int TokenInformation,
uint TokenInformationLength, out uint ReturnLength);
#endregion
#region Kernel32
[DllImport(Kernel32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern bool CloseHandle(IntPtr handle);
[DllImport(Kernel32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern IntPtr GetCurrentProcess();
[DllImport(Kernel32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern IntPtr GetCurrentThread();
[DllImport(Kernel32, CharSet = CharSet.Auto, SetLastError = true)]
public static extern SafeJobHandle CreateJobObject(IntPtr lpJobAttributes, string lpName);
[DllImport(Kernel32, SetLastError = true)]
public static extern bool SetInformationJobObject(SafeJobHandle hJob, JobObjectInfoType infoType,
ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION lpJobObjectInfo, int cbJobObjectInfoLength);
[DllImport(Kernel32, SetLastError = true)]
public static extern bool AssignProcessToJobObject(SafeJobHandle job, IntPtr process);
#endregion
#region Wtsapi
[DllImport(Wtsapi32, ExactSpelling = true, SetLastError = true)]
public static extern bool WTSQueryUserToken(int sessionid, out SafeTokenHandle handle);
#endregion
#region Userenv
[DllImport(Userenv, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CreateEnvironmentBlock(out EnvironmentBlockSafeHandle lpEnvironment, SafeTokenHandle hToken, bool bInherit);
[DllImport(Userenv, ExactSpelling = true, SetLastError = true)]
public extern static bool DestroyEnvironmentBlock(IntPtr hEnvironment);
#endregion
#region Structs
[StructLayout(LayoutKind.Sequential)]
public struct IO_COUNTERS
{
public ulong ReadOperationCount;
public ulong WriteOperationCount;
public ulong OtherOperationCount;
public ulong ReadTransferCount;
public ulong WriteTransferCount;
public ulong OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
public struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
public long PerProcessUserTimeLimit;
public long PerJobUserTimeLimit;
public uint LimitFlags;
public UIntPtr MinimumWorkingSetSize;
public UIntPtr MaximumWorkingSetSize;
public uint ActiveProcessLimit;
public UIntPtr Affinity;
public uint PriorityClass;
public uint SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public uint nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
public struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
public IO_COUNTERS IoInfo;
public UIntPtr ProcessMemoryLimit;
public UIntPtr JobMemoryLimit;
public UIntPtr PeakProcessMemoryUsed;
public UIntPtr PeakJobMemoryUsed;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
internal struct STARTUPINFO
{
public int cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public int dwX;
public int dwY;
public int dwXSize;
public int dwYSize;
public int dwXCountChars;
public int dwYCountChars;
public int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public uint LowPart;
public uint HighPart;
}
[StructLayout(LayoutKind.Sequential)]
public struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_PRIVILEGE
{
public uint PrivilegeCount;
public LUID_AND_ATTRIBUTES Privilege;
}
#endregion
#region Enums
public enum JobObjectInfoType
{
AssociateCompletionPortInformation = 7,
BasicLimitInformation = 2,
BasicUIRestrictions = 4,
EndOfJobTimeInformation = 6,
ExtendedLimitInformation = 9,
SecurityLimitInformation = 5,
GroupInformation = 11
}
public enum SecurityImpersonationLevel
{
Anonymous = 0,
Identification = 1,
Impersonation = 2,
Delegation = 3,
}
public enum TokenType
{
Primary = 1,
Impersonation = 2,
}
public enum TokenInformationClass
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
TokenIsAppContainer,
TokenCapabilities,
TokenAppContainerSid,
TokenAppContainerNumber,
TokenUserClaimAttributes,
TokenDeviceClaimAttributes,
TokenRestrictedUserClaimAttributes,
TokenRestrictedDeviceClaimAttributes,
TokenDeviceGroups,
TokenRestrictedDeviceGroups,
// MaxTokenInfoClass should always be the last enum
MaxTokenInfoClass
}
#endregion
#region SafeHandles
public sealed class EnvironmentBlockSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public EnvironmentBlockSafeHandle()
: base(true)
{
}
protected override bool ReleaseHandle()
{
return DestroyEnvironmentBlock(handle);
}
}
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public SafeTokenHandle()
: base(true)
{
}
override protected bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
internal sealed class SafeJobHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public SafeJobHandle()
: base(true)
{
}
protected override bool ReleaseHandle()
{
return CloseHandle(this.handle);
}
}
#endregion
}
}
Example Usage to create a process in another user's session:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Esatto.Win32.Processes
{
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
using static NativeMethods;
#if ESATTO_WIN32
public
#else
internal
#endif
static class ProcessInterop
{
public static void CreateProcessForSession(int sessionId, string exePath, string commandLine)
{
var privs = new[] { Privilege.TrustedComputingBase, Privilege.AssignPrimaryToken, Privilege.IncreaseQuota };
Privilege.RunWithPrivileges(() => CreateProcessForSessionInternal(sessionId, exePath, commandLine), privs);
}
private static void CreateProcessForSessionInternal(int sessionId, string exePath, string commandLine)
{
SafeTokenHandle hDupToken;
{
SafeTokenHandle hToken;
if (!WTSQueryUserToken(sessionId, out hToken))
{
throw new Win32Exception();
}
using (hToken)
{
if (!DuplicateTokenEx(hToken, TokenAccessLevels.AllAccess, IntPtr.Zero, SecurityImpersonationLevel.Impersonation, TokenType.Primary, out hDupToken))
{
throw new Win32Exception();
}
}
}
using (hDupToken)
{
EnvironmentBlockSafeHandle env;
if (!CreateEnvironmentBlock(out env, hDupToken, false))
{
throw new Win32Exception();
}
using (env)
{
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
PROCESS_INFORMATION procInfo;
if (!CreateProcessAsUser(hDupToken, new StringBuilder(exePath), new StringBuilder(commandLine),
IntPtr.Zero, IntPtr.Zero, false, NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT, env,
null, ref si, out procInfo))
{
throw new Win32Exception();
}
CloseHandle(procInfo.hProcess);
CloseHandle(procInfo.hThread);
}
}
}
public static int GetSessionId(this WindowsIdentity ident)
{
if (ident == null)
{
throw new ArgumentNullException();
}
int sessionId;
uint unused;
if (!GetTokenInformation(ident.Token, TokenInformationClass.TokenSessionId, out sessionId, 4, out unused))
{
throw new Win32Exception();
}
// since we are not passing a SafeHandle, we need to keep our reference on the SafeHandle
// contained in the WindowsIdentity
GC.KeepAlive(ident);
return sessionId;
}
}
}

C# LPT inpout32.dll

I don't get any error or exception.
Button in one Window:
private void button1_Click(object sender, EventArgs e)
{
ControlPort.Output(0x378, 0xff);
}
and inpout.dll interface:
class ControlPort
{
[DllImport("inpout32.dll", EntryPoint = "Out32")]
public static extern void Output(int adress, int value);
}
What is wrong?
LED on D2 is on all the time.
I have Windows 7 x64 Ultimate.
For x64 you should use "InpOutx64.dll".
Visit: http://www.highrez.co.uk/Downloads/InpOut32/default.htm
There you can read more and find samples.
Working code if somebody needs it.
using System;
using System.Runtime.InteropServices;
namespace ParallelPort
{
public class PortAccess
{
//inpout.dll
[DllImport("inpout32.dll")]
private static extern UInt32 IsInpOutDriverOpen();
[DllImport("inpout32.dll")]
private static extern void Out32(short PortAddress, short Data);
[DllImport("inpout32.dll")]
private static extern char Inp32(short PortAddress);
[DllImport("inpout32.dll")]
private static extern void DlPortWritePortUshort(short PortAddress, ushort Data);
[DllImport("inpout32.dll")]
private static extern ushort DlPortReadPortUshort(short PortAddress);
[DllImport("inpout32.dll")]
private static extern void DlPortWritePortUlong(int PortAddress, uint Data);
[DllImport("inpout32.dll")]
private static extern uint DlPortReadPortUlong(int PortAddress);
[DllImport("inpoutx64.dll")]
private static extern bool GetPhysLong(ref int PortAddress, ref uint Data);
[DllImport("inpoutx64.dll")]
private static extern bool SetPhysLong(ref int PortAddress, ref uint Data);
//inpoutx64.dll
[DllImport("inpoutx64.dll", EntryPoint = "IsInpOutDriverOpen")]
private static extern UInt32 IsInpOutDriverOpen_x64();
[DllImport("inpoutx64.dll", EntryPoint = "Out32")]
private static extern void Out32_x64(short PortAddress, short Data);
[DllImport("inpoutx64.dll", EntryPoint = "Inp32")]
private static extern char Inp32_x64(short PortAddress);
[DllImport("inpoutx64.dll", EntryPoint = "DlPortWritePortUshort")]
private static extern void DlPortWritePortUshort_x64(short PortAddress, ushort Data);
[DllImport("inpoutx64.dll", EntryPoint = "DlPortReadPortUshort")]
private static extern ushort DlPortReadPortUshort_x64(short PortAddress);
[DllImport("inpoutx64.dll", EntryPoint = "DlPortWritePortUlong")]
private static extern void DlPortWritePortUlong_x64(int PortAddress, uint Data);
[DllImport("inpoutx64.dll", EntryPoint = "DlPortReadPortUlong")]
private static extern uint DlPortReadPortUlong_x64(int PortAddress);
[DllImport("inpoutx64.dll", EntryPoint = "GetPhysLong")]
private static extern bool GetPhysLong_x64(ref int PortAddress, ref uint Data);
[DllImport("inpoutx64.dll", EntryPoint = "SetPhysLong")]
private static extern bool SetPhysLong_x64(ref int PortAddress, ref uint Data);
private bool _X64;
private short _PortAddress;
public PortAccess(short PortAddress)
{
_X64 = false;
_PortAddress = PortAddress;
try
{
uint nResult = 0;
try
{
nResult = IsInpOutDriverOpen();
}
catch (BadImageFormatException)
{
nResult = IsInpOutDriverOpen_x64();
if (nResult != 0)
_X64 = true;
}
if (nResult == 0)
{
throw new ArgumentException("Unable to open InpOut32 driver");
}
}
catch (DllNotFoundException)
{
throw new ArgumentException("Unable to find InpOut32.dll");
}
}
//Public Methods
public void Write(short Data)
{
if (_X64)
{
Out32_x64(_PortAddress, Data);
}
else
{
Out32(_PortAddress, Data);
}
}
public byte Read()
{
if (_X64)
{
return (byte)Inp32_x64(_PortAddress);
}
else
{
return (byte)Inp32(_PortAddress);
}
}
}
}
You are not going to get an exception when you get this wrong, at most a blue screen. Pick one of:
you are using the wrong address (0x3bc, 0x2f8)
you wired the LED wrong
you broke into the wrong museum to get the hardware
The question is too poorly documented to help you beyond this.
I resolved a problem with LPT port on Windows 2000 on my old laptop, where the data port (pin2-pin9) could not be set.
Using this imported function:
[DllImport("inpout32.dll", EntryPoint = "Out32")]
public static extern void Out32(int address, int value);
after every reboot or restart of Windows I have to call this line:
Out32(0x378 + 2, 0x00);
so that the port works properly. I think the problem is in the bi-directional settings (control port at 6th bit on 0x37A).

Categories

Resources