GithubHelp home page GithubHelp logo

dahall / vanara Goto Github PK

View Code? Open in Web Editor NEW
1.7K 40.0 190.0 127.18 MB

A set of .NET libraries for Windows implementing PInvoke calls to many native Windows APIs with supporting wrappers.

License: MIT License

C# 99.52% Visual Basic .NET 0.28% C++ 0.19% C 0.01%
pinvoke dotnet dotnet-standard controls windows extensions shell interop windows-api nuget

vanara's Introduction

Vanara

Version Downloads Build status

This project contains various .NET assemblies that contain P/Invoke functions, interfaces, enums and structures from Windows libraries. Each assembly is associated with one or a few tightly related libraries. For example, Shlwapi.dll has all the exported functions from shlwapi.lib; Kernel32.dll has all for both kernel32.lib and kernelbase.lib.

All assemblies are available via NuGet and provide builds against .NET 4.5, 4.8, 5.0, 6.0, .NET Standard 2.0, Core 3.1 and support SourceLink. Extensions are available for WinForms, WPF, and UWP projects. If you need support for other .NET versions, look to versions 3.3.15 and earlier.

This project releases new versions every few weeks after sufficient testing. New releases are cataloged, along with release notes, in the Releases section and all NuGet packages are published to nuget.org. Each GitHub push triggers an AppVeyor build. The owners thank them for the free Open-Source account! The status of that build is in the header of this page. The NuGet packages from those builds are available for test purposes on AppVeyor's project NuGet source at https://ci.appveyor.com/nuget/vanara-prerelease.

Use

  1. Look for the function you need in Microsoft documentation. Note which library or DLL the function is in.
  2. Confirm the Vanara library exists and has your function by looking at the Supported Libraries table below. Clicking on the Assembly link will take you to a drill down of that assembly's coverage. Find your function and if there is a matching implementation it will appear to the right. You can also use GitHub's project search (upper left of page) to search for your function, method or constant. Make sure to select "In this repository".
  3. Add the assembly to your project via NuGet.
  4. To use the function, you can:
    1. Call it directly var bret = Vanara.PInvoke.Kernel32.GetComputerName(sb, ref sbSz);
    2. Under C# 6.0 and later, use a static using directive and call it:
    using static Vanara.PInvoke.Kernel32;
    
    var bret = GetComputerName(sb, ref sbSz);
    
  5. In some cases there is a corresponding helper/wrapper class in one of the Supporting Assemblies, especially for Security, System Services, Forms and Shell. Go to their library page (click on link in section) and look through the classes included in each library.

Design Concepts

  • All functions that are imported from a single DLL should be placed into a single assembly that is named after the DLL.
    • (e.g. The assembly Vanara.PInvoke.Gdi32.dll hosts all functions and supporting enumerations, constants and structures that are exported from gdi32.dll in the system directory.)
  • Any structure or macro or enumeration (no function) that is used by many libraries is put into either Vanara.Core or Vanara.PInvoke.Shared.
    • (e.g. The macro HIWORD and the structure SIZE are both in Vanara.PInvoke.Shared and classes to simplify interop calls and native memory management are in Vanara.Core.)
  • Inside a project, all constructs are contained in a file named after the header file (*.h) in which they are defined in the Windows API.
    • (e.g. In the Vanara.PInvoke.Kernel32 project directory, you'll find a FileApi.cs, a WinBase.cs and a WinNT.cs file representing fileapi.h, winbase.h and winnt.h respectively.)
  • Where the direct interpretation of a structure or function leads to memory leaks or misuse, I have tried to simplify its use.
  • Where a structure is always passed by reference and where that structure needs to clean up memory allocations, I have changed the structure to a class implementing IDisposable.
  • Wherever possible, all handles have been turned into SafeHandle derivatives named after the Windows API handle. If those handles require a call to a function to release/close/destroy, a derived SafeHANDLE exists that performs that function on disposal.
    • e.g. HTOKEN is defined. SafeHTOKEN builds upon that handle with an automated release calling CloseHandle.
  • Wherever possible, all functions that allocate memory that is to be freed by the caller use a safe memory handle.
  • All PInvoke calls are in assemblies prefixed by Vanara.PInvoke.
  • If a structure is to passed into a function as a constant, that structure is marshaled using the in statement which will pass the structure by reference without requiring the ref keyword.
    • Windows API: BOOL MapDialogRect(HWND hDlg, LPRECT lpRect)
    • Vanara: bool MapDialogRect(HWND hDlg, in RECT lpRect);
  • If there are classes or extensions that make use of the PInvoke calls, they are in wrapper assemblies prefixed by Vanara and then followed by a logical name for the functionality. Today, those are Core, Security, SystemServices, Windows.Forms and Windows.Shell.

Supported Libraries

Library/DLL Assembly Coverage NuGet Link       
aclui.dll Vanara.PInvoke.AclUI Coverage NugetNuget
advapi32.dll, secur32.dll, authz.dll, sspicli.dll, schannel.dll, tdh.dll Vanara.PInvoke.Security Coverage NugetNuget
amsi.dll Vanara.PInvoke.AMSI Coverage NugetNuget
avicap32.dll, avifil32.dll, msacm32.dll, msvfw32.dll, winmm.dll Vanara.PInvoke.Multimedia Coverage NugetNuget
avrt.dll Vanara.PInvoke.Avrt Coverage NugetNuget
cabinet.dll Vanara.PInvoke.Cabinet Coverage NugetNuget
CfgMgr32.dll Vanara.PInvoke.CfgMgr32 Coverage NugetNuget
cimfs.dll Vanara.PInvoke.CimFs Coverage NugetNuget
CldApi.dll Vanara.PInvoke.CldApi Coverage NugetNuget
clfsw32.dll Vanara.PInvoke.ClfsW32 Coverage NugetNuget
comctl32.dll Vanara.PInvoke.ComCtl32 Coverage NugetNuget
ComDlg32.dll Vanara.PInvoke.ComDlg32 Coverage NugetNuget
credui.dll Vanara.PInvoke.CredUI Coverage NugetNuget
crypt32.dll, bcrypt.dll, ncrypt.dll, tokenbinding.dll, cryptui.dll, cryptnet.dll, cryptdlg.dll Vanara.PInvoke.Cryptography Coverage NugetNuget
d2d1.dll, dxgi.dll, dwrite.dll, windowscodecs.dll Vanara.PInvoke.Graphics Coverage NugetNuget
davclnt.dll Vanara.PInvoke.DavClnt Coverage NugetNuget
DbgHelp.dll, ImageHlp.dll Vanara.PInvoke.DbgHelp Coverage NugetNuget
Dhcpcsvc6.dll, Dhcpcsvc.dll Vanara.PInvoke.Dhcp Coverage NugetNuget
DnsApi.dll Vanara.PInvoke.DnsApi Coverage NugetNuget
dosvc.dll Vanara.PInvoke.DOSvc Coverage NugetNuget
drt.dll, drtprov.dll, drttransport.dll Vanara.PInvoke.Drt Coverage NugetNuget
dwmapi.dll Vanara.PInvoke.DwmApi Coverage NugetNuget
ehstorapi.dll Vanara.PInvoke.EnhancedStorage Coverage NugetNuget
fhsvcctl.dll Vanara.PInvoke.FhSvcCtl Coverage NugetNuget
FirewallApi.dll Vanara.PInvoke.FirewallApi Coverage NugetNuget
FunDisc.dll Vanara.PInvoke.FunDisc Coverage NugetNuget
fwpuclnt.dll Vanara.PInvoke.FwpUClnt Coverage NugetNuget
gdi32.dll Vanara.PInvoke.Gdi32 Coverage NugetNuget
httpapi.dll Vanara.PInvoke.HttpApi Coverage NugetNuget
imapi2.dll, imapi2fs.dll Vanara.PInvoke.IMAPI Coverage NugetNuget
imm32.dll Vanara.PInvoke.Imm32 Coverage NugetNuget
iphlpapi.dll Vanara.PInvoke.IpHlpApi Coverage NugetNuget
IScsiDsc.dll Vanara.PInvoke.IScsiDsc Coverage NugetNuget
kernel32.dll, kernelbase.dll, normaliz.dll, vertdll.dll Vanara.PInvoke.Kernel32 Coverage NugetNuget
ktmw32.dll Vanara.PInvoke.KtmW32 Coverage NugetNuget
Lz32.dll Vanara.PInvoke.Lz32 Coverage NugetNuget
magnification.dll Vanara.PInvoke.Magnification Coverage NugetNuget
mmdevapi.dll Vanara.PInvoke.CoreAudio Coverage NugetNuget
mpr.dll Vanara.PInvoke.Mpr Coverage NugetNuget
msctf.dll, input.dll, msimtf.dll Vanara.PInvoke.TextServicesFramework Coverage NugetNuget
Msi.dll Vanara.PInvoke.Msi Coverage NugetNuget
MsRdc.dll Vanara.PInvoke.MsRdc Coverage NugetNuget
ndfapi.dll Vanara.PInvoke.NdfApi Coverage NugetNuget
netapi32.dll Vanara.PInvoke.NetApi32 Coverage NugetNuget
netprofm.dll Vanara.PInvoke.NetListMgr Coverage NugetNuget
NewDev.dll Vanara.PInvoke.NewDev Coverage NugetNuget
ntdll.dll Vanara.PInvoke.NtDll Coverage NugetNuget
ntdsapi.dll Vanara.PInvoke.NTDSApi Coverage NugetNuget
ole32.dll, oleaut32.dll, propsys.dll Vanara.PInvoke.Ole Coverage NugetNuget
oleacc.dll Vanara.PInvoke.Accessibility Coverage NugetNuget
OleDlg.dll Vanara.PInvoke.OleDlg Coverage NugetNuget
opcservices.dll Vanara.PInvoke.Opc Coverage NugetNuget
P2P.dll Vanara.PInvoke.P2P Coverage NugetNuget
pdh.dll Vanara.PInvoke.Pdh Coverage NugetNuget
PeerDist.dll Vanara.PInvoke.PeerDist Coverage NugetNuget
portabledeviceapi.dll, portabledeviceconnectapi.dll, portabledevicetypes.dll Vanara.PInvoke.PortableDeviceApi Coverage NugetNuget
powrprof.dll Vanara.PInvoke.PowrProf Coverage NugetNuget
ProjectedFSLib.dll Vanara.PInvoke.ProjectedFSLib Coverage NugetNuget
qmgr.dll Vanara.PInvoke.BITS Coverage NugetNuget
qwave.dll, traffic.dll Vanara.PInvoke.QoS Coverage NugetNuget
rpcrt4.dll Vanara.PInvoke.Rpc Coverage NugetNuget
RstrtMgr.dll Vanara.PInvoke.RstrtMgr Coverage NugetNuget
SearchApi Vanara.PInvoke.SearchApi Coverage NugetNuget
sensorsapi.dll Vanara.PInvoke.SensorsApi Coverage NugetNuget
SetupAPI.dll Vanara.PInvoke.SetupAPI Coverage NugetNuget
SHCore.dll Vanara.PInvoke.SHCore Coverage NugetNuget
shell32.dll, url.dll Vanara.PInvoke.Shell32 Coverage NugetNuget
shlwapi.dll Vanara.PInvoke.ShlwApi Coverage NugetNuget
taskschd.dll, mstask.dll Vanara.PInvoke.TaskSchd Coverage NugetNuget
UrlMon.dll Vanara.PInvoke.UrlMon Coverage NugetNuget
user32.dll Vanara.PInvoke.User32 Coverage NugetNuget
UserEnv.dll Vanara.PInvoke.UserEnv Coverage NugetNuget
usp10.dll Vanara.PInvoke.Usp10 Coverage NugetNuget
uxtheme.dll Vanara.PInvoke.UxTheme Coverage NugetNuget
Version.dll Vanara.PInvoke.Version Coverage NugetNuget
virtdisk.dll Vanara.PInvoke.VirtDisk Coverage NugetNuget
vssapi.dll Vanara.PInvoke.VssApiMgd Coverage NugetNuget
WcmApi.dll Vanara.PInvoke.WcmApi Coverage NugetNuget
WcnApi.dll Vanara.PInvoke.WcnApi Coverage NugetNuget
websocket.dll Vanara.PInvoke.WebSocket Coverage NugetNuget
wer.dll Vanara.PInvoke.Wer Coverage NugetNuget
WinBio.dll Vanara.PInvoke.WinBio Coverage NugetNuget
winhttp.dll Vanara.PInvoke.WinHTTP Coverage NugetNuget
wininet.dll Vanara.PInvoke.WinINet Coverage NugetNuget
winscard.dll Vanara.PInvoke.WinSCard Coverage NugetNuget
winspool.drv, prntvpt.dll Vanara.PInvoke.Printing Coverage NugetNuget
wintrust.dll Vanara.PInvoke.WinTrust Coverage NugetNuget
WlanApi.dll, Wlanui.dll Vanara.PInvoke.WlanApi Coverage NugetNuget
ws2_32.dll Vanara.PInvoke.Ws2_32 Coverage NugetNuget
wscapi.dll Vanara.PInvoke.WscApi Coverage NugetNuget
WsmSvc.dll Vanara.PInvoke.WsmSvc Coverage NugetNuget
WTSApi32.dll Vanara.PInvoke.WTSApi32 Coverage NugetNuget

Supporting Assemblies

Assembly    NuGet Link    Description
Vanara.BITS NugetNuget Complete .NET coverage of Windows BITS (Background Intelligent Transfer Service) functionality. Provides access to all library functions through Windows 11 and gracefully fails when new features are not available on older OS versions.
Vanara.Core NugetNuget This library includes shared methods, structures and constants for use throughout the Vanara assemblies. Think of it as windows.h with some useful extensions. It includes:
* Extension methods for working with enumerated types (enum), FILETIME, and method and property extractions via reflection
* Extension and helper methods to marshaling structures arrays and strings
* SafeHandle based classes for working with memory allocated via CoTaskMem, HGlobal, or Local calls that handles packing and extracting arrays, structures and raw memory
* Safe pinning of objects in memory
* Memory stream based on marshaled memory
Vanara.Management NugetNuget Extensions and helper classes for System.Management.
Vanara.Net NugetNuget Abstracted classes around Win32 networking functions to provide simplified and object-oriented access to key networking capabilities like DNS, DHCP, filtering, access, and discovery.
Vanara.PInvoke.PhotoAcquire NugetNuget PInvoke API (methods, structures and constants) imported from Windows Photo Acquisition.
Vanara.PInvoke.Shared NugetNuget Shared methods, structures and constants for use throughout the Vanara.PInvoke assemblies. Includes:
* IEnumerable helpers for COM enumerations
* Custom marshaler for CoTaskMem pointers
* Enhanced error results classes for HRESULT, Win32Error and NTStatus
* Standard windows.h macros (e.g. HIWORD, MAKELONG, etc.)
* Overlapped method wrapper
* Resource ID holder
* Shared structures and enums (see release notes)
Vanara.Security NugetNuget Classes for security related items derived from the Vanara PInvoke libraries. Includes extension methods for Active Directory and access control classes, methods for working with accounts, UAC, privileges, system access, impersonation and SIDs, and a full LSA wrapper.
Vanara.SystemServices NugetNuget Classes for system related items derived from the Vanara PInvoke libraries. Includes extensions for Process (privileges and elavation), FileInfo (compression info), Shared Network Drives and Devices, and ServiceController (SetStartType) that pull extended information through native API calls.
Vanara.VirtualDisk NugetNuget .NET classes to manage Windows Virtual Storage (VHD and VHDX) using P/Invoke functions from VirtDisk.dll.
Vanara.Windows.Extensions NugetNuget Extension methods and conversions from Vanara P/Invoke types and methods to Windows Forms types and methods.
Vanara.Windows.Forms NugetNuget Classes for user interface related items derived from the Vanara PInvoke libraries. Includes extensions for almost all common controls to give post Vista capabilities, WinForms controls (panel, commandlink, enhanced combo boxes, IPAddress, split button, trackbar and themed controls), shutdown/restart/lock control, buffered painting, resource files, access control editor, simplifed designer framework for Windows.Forms.
Vanara.Windows.Shell.Common NugetNuget Common classes for Windows Shell items derived from the Vanara PInvoke libraries. Includes shell items, files, icons, links, and taskbar lists.
Vanara.Windows.Shell NugetNuget Classes for Windows Shell items derived from the Vanara PInvoke libraries. Includes shell items, files, icons, links, and taskbar lists.
Vanara.WinUI.Extensions NugetNuget Extension methods and conversions from Vanara P/Invoke types and methods to UWP and WinUI types and methods.
Vanara.WPF.Extensions NugetNuget Extension methods and conversions from Vanara P/Invoke types and methods to WPF types and methods.

Quick Links

Sample Code

There are numerous examples in the UnitTest folder and in the WinClassicSamplesCS project that recreates the Windows Samples in C# using Vanara.

vanara's People

Contributors

5cover avatar andregleichner avatar cuft avatar dahall avatar gigi81 avatar greatfirewall avatar jeanbern avatar mantaspau98 avatar marklechtermann avatar martinkuschnik avatar mihaicodrean avatar nn--- avatar pazerop avatar peppy avatar propagating avatar psulek avatar rmeshksar avatar sbarrac avatar shirok1 avatar tajbender avatar threesevenths avatar tonyhallett avatar vessd avatar wjk avatar xh321 avatar yomodo avatar zhuxb711 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vanara's Issues

Join Project With AArnott/pinvoke?

I am currently working on a project that needs some Win32 API access from c#. I've chosen the Arnott/pinvoke project now, just because it covers a lot, is actively maintained AND had the most downloads. Your projects covers the same area, maybe not will full identical functionality.
Maybe with some other philosophy. I hadn't the time to deeply find differences.

Have thought about joining your project with the Arnott/pinvoke? For me it looks like the pinvoke has a lot of contributors and pull request are handled very positive and with good feedback.

Best wishes
Marco

Remove case inconsistency on Folder 'PInvoke/NtDll' to avoid misleading TortoiseGIT-status

Case insensitivity of folder 'PInvoke/NtDll' causes Windows-Tools like TortoiseGIT to show incorrect 'Changes pending' status.

I'm using TortoiseGIT to keep track of my working copies, and as I checked out a clean copy of Vanara's master branch, I found that TortoiseGIT shows a misleading 'Changes pending' status icon on folder 'Vanara/PInvoke'.

If you then ask what changes TrotoiseGIT claims to be made to the project via 'Git check for modifications', you won't see any changes.

Digging further I've found out that there is a case inconsistency of sub-folder 'PInvoke/NtDll'. Browsing the repository I've found two different versions, 'NTDll' and 'NtDll'. However, since windows based file systems still treat both variations as the same folder, the content of both folders will be created in the same folder when checking out.

Tools like TortoiseGIT then get confused by this, and finally show pending changes where there are none. See attached screenshot for clarification:

vanara - pr 30

ApplicationException always occur while calling DeviceIoControlAsync using same hDevice at 2nd time

Describe the bug
As Title.

What code is involved
Kernel32.DeviceIoControlAsync -> Kernel32.BeginDeviceIoControl -> OverlappedAsync.SetupOverlappedFunction

How to reproduce

var device = Kernel32.CreateFile(@"\\.\DeviceDriverName", 
                                 Kernel32.FileAccess.GENERIC_READ | Kernel32.FileAccess.GENERIC_WRITE,
                                 System.IO.FileShare.None,
                                 null,
                                 System.IO.FileMode.Open,
                                 FileFlagsAndAttributes.FILE_FLAG_OVERLAPPED);

await Kernel32.DeviceIoControlAsync(device, someIoControlCode, ...);
await Kernel32.DeviceIoControlAsync(device, someIoControlCode, ...);  // exception thrown here

Screenshots

image

image

CreateRemoteThread doesn't receive IntPtr for the routine

CreateRemoteThread doesn't receive IntPtr as routine parameter.
It is not possible to pass a pointer.
E.g.:

IntPtr llAddress = Kernel32.GetProcAddress(Kernel32.GetModuleHandle("kernel32.dll"), "LoadLibraryA"); 

// Not possible to pass llAddress
Kernel32.CreateRemoteThread(pi.hProcess, null, 0, (Kernel32.PTHREAD_START_ROUTINE)llAddress, remoteMemory, 0, out var remoteThreadId);

GetThemeStream causes a heap corruption and crashes app

Using the GetThemeStream function from the UxTheme class causes the app to crash with exit code 0xc0000374 (heap corruption).

I've been using these two links as a guide:
Windows 10 Close, Minimize and Maximize buttons - StackOverflow
GetThemeStream usage - StackOverflow

I'm not sure what I'm doing wrong, but something really weird is happening.

Thanks for you time.

static void Main()
{
    const int WP_MINCAPTION = 3;
    const int MNCS_ACTIVE = 1;
    const int TMT_ATLASRECT = 8002;


    var w = new NativeWindow();
    CreateParams cp = new CreateParams();
    w.CreateHandle(cp);

    byte[] themeStream;
    int streamSize;

    var h = UxTheme.OpenThemeData(new HandleRef(w, w.Handle), "DWMWINDOW");

    Vanara.PInvoke.Kernel32.SafeLibraryHandle hInstance = null;


    if (!h.IsInvalid)
    {
        try
        {
            RECT rect;

            UxTheme.GetThemeRect(h, WP_MINCAPTION, MNCS_ACTIVE, TMT_ATLASRECT, out rect);

            hInstance = Kernel32.LoadLibraryEx(@"C:\Windows\resources\themes\Aero\Aero.msstyles", dwFlags: Kernel32.LoadLibraryExFlags.LOAD_LIBRARY_AS_DATAFILE);

            UxTheme.GetThemeStream(h, WP_MINCAPTION, MNCS_ACTIVE, TMT_ATLASRECT, out themeStream, out streamSize, hInstance);
        }
        finally
        {
            Kernel32.FreeLibrary(hInstance);
            UxTheme.CloseThemeData(h);
        }

    }
    w.DestroyHandle();
}

System.Threading package and Theraot.Core package have type conflict

I am use Visual Studio 2013 and target .Net 3.5 .

I need some fun supported by Task,Lazy,BlockingCollection and many more.

But when i reference Vanara.PInvoke.IpHlpApi from NuGet, it depend the Theraot.Core package.

So compiler give some errors:

The type 'System.Lazy' exists in both \TaskParallelLibrary.1.0.2856.0\lib\Net35\System.Threading.dll
and \Theraot.Core.2.1.0\lib\NET35\Theraot.Core.dll'

The type 'System.Threading.Tasks.Task' exists in both \TaskParallelLibrary.1.0.2856.0\lib\Net35\System.Threading.dll and \Theraot.Core.2.1.0\lib\NET35\Theraot.Core.dll

System.Threading.Tasks.TaskCreationOptions exists in both \TaskParallelLibrary.1.0.2856.0\lib\Net35\System.Threading.dll and \Theraot.Core.2.1.0\lib\NET35\Theraot.Core.dll

......

So I try to modify System.Threading's aliases properties. Too many modifications and the compiler give errors too.

So I try to modify Theraot.Core's aliases properties. Build succeeded.
There may be potential runtime issues.

what is the best way? Thanks.

User32_Gdi parameter type improvements

I have been making use of User32_Gdi recently and feel that some of the parameter types could be improved. Some examples that I've come across are:

  1. The nIndex parameter of SetWindowLong and GetWindowLong could be WindowLongFlags.
  2. There is no overload of SendMessage that accepts a WindowMessage as msg with defaults for wParam and lParam.
  3. Having to create an IntPtr when calling SetWindowLong is annoying; perhaps it could accept an enum and do the conversion internally.
  4. I don't think WindowLongFlags should be flags as it is specifying the value to retrieve.

[UxTheme.dll] GetThemeBitmap function is outdated

Hello, according to the MSDN, the GetThemeBitmap pinvoke is outdated.

Probably there are more functions that don't need the hDc argument.

According to the MSDN:

HRESULT GetThemeBitmap(
  _In_  HTHEME  hTheme,
  _In_  int     iPartId,
  _In_  int     iStateId,
  _In_  int     iPropId,
  _In_  ULONG   dwFlags,
  _Out_ HBITMAP *phBitmap
);

Your P/Invoke:

HRESULT GetThemeBitmap(
  UxTheme.SafeThemeHandle hTheme,
  Gdi32.SafeDCHandle hdc,
  int iPartId,
  int iStateId,
  int iPropId,
  int dwFlags,
  out IntPtr phBitmap
);

When running the code, this can be confirmed by Visual Sudio's Managed Debugging Assistant:

Managed Debugging Assistant 'PInvokeStackImbalance' :
'A call to PInvoke function 'Vanara.PInvoke.UxTheme!Vanara.PInvoke.UxTheme::GetThemeBitmap' has unbalanced the stack.
This is likely because the managed PInvoke signature does not match the unmanaged target signature.
Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.'

Thank you for the time you put to make this project into something really good and usable.

PreventShutdownContext does not work.

Describe the bug
PreventShutdownContext does not prevent the user from shutting down the system and no dialog window is shown.

This does not seem a bug, but I think the author must improve its implementation to determine at runtime whether or not using PreventShutdownContext will really prevent the shutdown (and then throw an exception or something when the instance is initialized, this way the end-user can catch it to be aware that the system CAN be shutdown during a critical operation), but for improving that first we should figure why it is not preventing shutdown... and I don't have idea about why it does not.

What code is involved
WIndows.Forms/Contexts/PreventShutdownContext.cs

Expected behavior
You know...

Screenshots
Better than a screenshot:
https://stackoverflow.com/questions/54842853/calling-shutdownblockreasoncreate-function-does-not-prevent-the-user-from-shut

TypeLoadException due to BLOCK_REGION_UNION

Describe the bug

System.TypeLoadException
  HResult=0x80131522
  Message=Could not load type 'BLOCK_REGION_UNION' from assembly 'Vanara.PInvoke.Kernel32, Version=2.3.10.0, Culture=neutral, PublicKeyToken=c37e4080322237fa' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.

What code is involved
No code, simply referencing several of the Vanara assemblies seems to trigger it. Not exactly sure which, but my project is referencing these:

  • Vanara.PInvoke.Mpr
  • Vanara.PInvoke.NtDll
  • Vanara.PInvoke.Shell32
  • Vanara.PInvoke.User32
  • Vanara.PInvoke.User32.Gdi
  • Vanara.PInvoke.WinINet

(And all dependencies of these.)

Expected behavior
No TLE.

Kernel32.DeviceIoControlAsync stuck at EndOverlappedFunction -> handle.WaitOne();

Describe the bug

All Kernel32.DeviceIoControlAsync( ... ) always stuck at

public static object EndOverlappedFunction(IAsyncResult asyncResult)
{
    ...
    handle.WaitOne(); // stuck here
    ...
}

How to reproduce

See the following image.

The Kernel32.DeviceIoControlAsync<EmptyStruct>(device, 0x282004) I can change to any other ioControlCode that already implementation in my driver, always stuck too.

The DeviceIoControl (without async) works well. So I infer that it's not my driver's problem.

image

Now debug this unit test method:

gif

OK, let's try add a delay between CloseDevice and OpenDevice like this:

image

Debug again:

gif

No stuck now. 🤔

WriteProcessMemory receiving byte array

In addition to IntPtr overload there should be byte[] overload:

	public static extern bool WriteProcessMemory([In] HPROCESS hProcess, [In] IntPtr lpBaseAddress, [In] byte[] lpBuffer, SizeT nSize, out SizeT lpNumberOfBytesWritten);

AuthzEnumerateSecurityEventSources help

I think I found what I needed in the AuthzEnumerateSecurityEventSourcesTest method but I'm not sure it's best practice to just assume 200 is big enough. I was assuming I'd have to call the API once to get the count and then allocate that many. But I don't really know this API well enough to say that for a fact.

Originally posted by @chrpai in #8 (comment)

AdvApi32 CredEnumerate marshals error

Describe the bug
AdvApi32.CredEnumerate call is not functionning, throwing an System.ExecutionEngineException: 'Exception of type 'System.ExecutionEngineException' was thrown.'

What code is involved
AdvApi32.CredEnumerate and after some fast research underlying handle.ToArray

Expected behavior
Returning a array of Credential object.

Other
Some CredAPI could be impr. and a PR is on this way too.

Problem using IExplorerBrowserEvents and SafeHandles: SafeHandles cannot be marshaled from unmanaged to managed

Hello mates,

currently I'm converting my WindowsExplorer-Replacement to use Vanara 2.1.0 wherever possible. So I implemented a Wrapper for ExplorerBrowser as seen e.g. in the Windows-API-Code-Pack.

What code is involved
To get the ExplorerBrowser to work, I had to implement a class defining the following interfaces:

  • Vanara.PInvoke.Shell32.IServiceProvider
  • Vanara.PInvoke.Shell32.IExplorerPaneVisibility
  • Vanara.PInvoke.Shell32.IExplorerBrowserEvents
  • Vanara.PInvoke.Shell32.ICommDlgBrowser3

Expected behavior
Using IExplorerBrowserEvents, my code should get noticed before trying to browse to a folder.

Describe the bug
However, when trying to do so I get the following runtime exception:

Managed Debugging Assistant 'InvalidMemberDeclaration' Message=Managed Debugging Assistant 'InvalidMemberDeclaration' : 'The following error occurred while determining how to marshal the parameters of member 'OnNavigationPending' of type 'IExplorerBrowserEvents': System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #1': SafeHandles cannot be marshaled from unmanaged to managed. This is most likely due to an incompatible MarshalAs attribute on one of the parameters. '

Final Thoughts
Since I'm new to Vanara, I really don't get the point where to fix this. Sorry if I'm wrong, but my assumption is, that since public void OnNavigationPending(Shell32.PIDL pidlFolder) { System.Windows.Forms.MessageBox.Show("OnNavigationPending!"); }
is called by Window Explorer's ExplorerBrowser-Implementation, the Marshaller can't marshal the native PIDL-Pointer back to Vanara's safe Implementation of a PIDL.

Any ideas on this would be very appreciated! Thanks in advance,
tajbender

GetHandler<IStream> hangs after getting property from ShellItem

After getting a ShellItem for a file, I get the MIMEType property followed by opening the file using GetHandler. The app hangs on the call to GetHandler

If I new a ShellItem (from a PIDL) for the properties call and new another ShellItem for the GetHandler it works fine

What code is involved
Calling ShellItem.GetHandler after ShellItem.Properties.TryGetValue

Expected behavior
GetHandler should return an IStream

using (var shellItem = new ShellItem(this.SelectedItem.pidl))
{
    if (!shellItem.IsFolder)
    {
            if (shellItem.Properties.TryGetValue<string>(PROPERTYKEY.System.MIMEType, out var val))
            {
                System.Diagnostics.Trace.WriteLine(val);
            }
        }

        // calling this after the properties hangs - don't know why
        var storage = shellItem.GetHandler<IStream>(BHID.BHID_Stream);
        try
        {
            // IStreamStream  wraps IStream with a .NET Stream
            using (var stream = new IStreamStream(storage))
            using (var sr = new StreamReader(stream))
            {
                System.Diagnostics.Trace.WriteLine($"{shellItem.FileSystemPath} ({stream.Length})");
            }
        }
        finally
        {
            Marshal.ReleaseComObject(storage);
        }
    }
}

SafeHandle overloads

Functions receiving IntPtr should receive SafeHandle instead.

E.g. instead of

public static extern bool CreateProcessAsUser(IntPtr hToken, ...)

It is better to have

public static extern bool CreateProcessAsUser(SafeTokenHandle hToken, ...)

Nowadays everyone is using safe handles, so converting back and forth is not only unnecessary but may introduce bugs.

GetInfo<IntPtr> throws InvalidCastException for TOKEN_INFORMATION_CLASS.TokenLinkedToken

Describe the bug
UAC.IsRunningAsAdmin throws InvalidCastException.

What code is involved
It basically gets down to:

hObject.GetInfo<IntPtr>()

The GetInfo() expects a CorrespondingTypeAttribute on the enum value of TOKEN_INFORMATION_CLASS-enum which is TOKEN_LINKED_TOKEN for TOKEN_INFORMATION_CLASS.TokenLinkedToken.
As IntPtr is no TOKEN_LINKED_TOKEN this method throws the invalid cast exception.

Digging down the rabbit hole:
GetInfo<TOKEN_LINKED_TOKEN> will return IntPtr.Zero due to

if (typeof(T) == typeof(IntPtr))

in https://github.com/dahall/Vanara/blob/master/PInvoke/Security/AdvApi32/SecurityBaseApi.cs#L1395
Thus GetInfo<TOKEN_LINKED_TOKEN> cannot be used here.

Expected behavior
IntPtr value is returned.

Naively assumed GitHub would create this issue correctly using "Reference in new issue" which apparently does not work.
Direct link to erroring source: https://github.com/dahall/Vanara/blob/master/Security/UAC.cs#L82

MarshalDirectiveException when using CommandLineToArgvW()

Describe the bug

Cannot marshal 'return value': Invalid managed/unmanaged type combination.
  + Vanara.PInvoke.Shell32.CommandLineToArgvW(string, out int)

What code is involved

> #r "Vanara.PInvoke.Shell32.dll"
> using Vanara.PInvoke;
> Shell32.CommandLineToArgvW("", out _)

Expected behavior
No exception.

Add SecureZeroMemory

There are a number of methods that suggest calling SecureZeroMemory e.g. CredUIPromptForCredentials. I can't find anywhere that you've provided this (I might be missing it)? I think it would be good to provide it. Perhaps something like this:

/// <summary>
/// Fills a block of memory with zeros.
/// </summary>
/// <remarks>
/// SecureZeroMemory is an alias of RtlSecureZeroMemory, an inline function defined in
/// WinBase. Neither SecureZeroMemory or RtlSecureZeroMemory are exported as a function from
/// a dll. This method is intended to mimic it's behaviour.
/// </remarks>
/// <param name="pointer">
/// A pointer to the starting address of the block of memory to fill with zeros.
/// </param>
/// <param name="bufferSize">The size of the block of memory to fill with zeros, in bytes.</param>
private static void SecureZeroMemory(IntPtr pointer, uint bufferSize)
{
    Marshal.Copy(new byte[bufferSize], 0, pointer, (int)bufferSize);
}

Would it be possible to update the function comments to point to the new method e.g. InteropServices.SecureZeroMemory?

Unable to obtain sid from ace

I am trying to utilize the provided methods to obtain the SID from an ACE without utilizing direct native code:

var error = GetNamedSecurityInfo(
    "\\\\?\\C:\\tmp\\sec",
    SE_OBJECT_TYPE.SE_FILE_OBJECT,
    SECURITY_INFORMATION.DACL_SECURITY_INFORMATION,
    out PSID ppsidOwner,
    out PSID ppsidGroup,
    out PACL ppDacl,
    out PACL ppSacl,
    out SafeSecurityDescriptor ppSecurityDescriptor);

var aclSizeInformation = new ACL_SIZE_INFORMATION();
var result = GetAclInformation(ppDacl, ref aclSizeInformation);
for (int i = 0; i < aclSizeInformation.AceCount; i++)
{
    ACCESS_ALLOWED_ACE ace = GetAce(ppDacl, i);
    // Obtain sid?
}

However, when using AdvApi32.GetAce(PACL pAcl, int dwAceIndex, out PACE pAce) instead of the helper above, I can use the underlying handle and obtain the binary sid for use with LookupAccountSid(string lpSystemName, byte[] lpSid, StringBuilder lpName, ref int cchName, StringBuilder lpReferencedDomainName, ref int cchReferencedDomainName, out SID_NAME_USE peUse).

What facility exists utilizing the library without any direct native calls?

DeviceIoControlAsync incorrent pointer offset of input/output buffer

Hi, forgive me for my broken English.

Describe the bug
DeviceIoControlAsync incorrent pointer offset of input/output buffer.

What code is involved
Vanara.PInvoke.Kernel32.DeviceIoControlAsync at line 133 in file Vanara\PInvoke\Kernel32\IoApiSet.Threading.cs

Vanara.PInvoke.Kernel32.Pack at line 915 in file Vanara\PInvoke\Kernel32\IoApiSet.cs

Vanara.PInvoke.Kernel32.BeginDeviceIoControl at line 887 in file Vanara\PInvoke\Kernel32\IoApiSet.cs

Expected behavior
Rather than the buf that contains struct lengths wrote in
Vanara\PInvoke\Kernel32\IoApiSet.cs at line 915:

private static byte[] Pack<TIn, TOut>(TIn? inVal, TOut? outVal) where TIn : struct where TOut : struct
{
   using (var ms = new MemoryStream())
   using (var wtr = new BinaryWriter(ms))
   {
      wtr.Write(inVal.HasValue ? Marshal.SizeOf(typeof(TIn)) : 0);
      wtr.Write(outVal.HasValue ? Marshal.SizeOf(typeof(TOut)) : 0);
      if (inVal.HasValue) wtr.Write(inVal.Value);
      if (outVal.HasValue) wtr.Write(outVal.Value);
      return ms.ToArray();
   }
}

, the DeviceIoControlAsync should pass a buf that skips the lengths of TIn and TOut

Screenshots

image

image

Kernel32.WaitForDebugEventEx throws TypeLoadException

Describe the bug
Attempting to use the Kernel32.WaitForDebugEventEx API results in this exception:

Unhandled Exception: System.TypeLoadException: Could not load type 'EXCEPTION_INFO' from assembly 'Vanara.PInvoke.Kernel32, Version=2.3.8.0, Culture=neutral, PublicKeyToken=c37e4080322237fa' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.

What code is involved
Something along these lines:

if (Kernel32.DebugActiveProcess(pid))
    while (Kernel32.WaitForDebugEventEx(out var ev, Kernel32.INFINITE))
        Kernel32.ContinueDebugEvent(ev.dwProcessId, ev.dwThreadId, Kernel32.DEBUG_CONTINUE.DBG_CONTINUE);

Expected behavior
No TypeLoadException.

SafeHFILE != null issue.

Version: v2.2.1

Describe the bug

Kernel32.SafeHFILE device = null;
if (device != null)
    Console.WriteLine("Always here."); // this is not expected

Expected behavior
default(Kernel32.SafeHFILE) == null // be true

Screenshots

image

image

Root cause of problem

image

ReadConsoleInput and associated structures not marshalling data correctly

Describe the bug
ReadConsoleInput, when reading KEY_EVENT, the bKeyDown flag is always TRUE for both keyup and keydown. I've noticed in other scenarios the event type flag is always 0 - I think perhaps your automated conversion (I assume you're using something automated here) is messing up.

What code is involved
Kernel32.ReadConsoleInput and INPUT_RECORD

Expected behavior
bKeyDown should reflect keydown events correctly.

Screenshots
I replaced your library with the definitions here and everything works fine.
http://www.pinvoke.net/default.aspx/kernel32/ConsoleFunctions.html

Thanks for an otherwise outstanding and clean library.

ControlPanel.GetPath Exception

I get an exception when trying to use ControlPanel.GetPath

Sample code:
ControlPanelItem cpi = ControlPanelItem.AutoPlay;
string path = ControlPanel.GetPath(cpi);

Exception:
Message: Error HRESULT E_FAIL has been returned from a call to a COM component.
Source: Vanara.PInvoke.Shell32
StackTrace: at Vanara.PInvoke.Shell32.IOpenControlPanel.GetPath(String pszName, StringBuilder pszPath, UInt32 cchPath) at Vanara.Windows.Shell.ControlPanel.GetPath(String item) at Vanara.Windows.Shell.ControlPanel.GetPath(ControlPanelItem item)

This is in a WPF project VS 2017 CE, Windows 10 64bit

Why Vanara.PInvoke.User32.Gdi does not support .NETStandard 2.0

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the additions or enhancements you'd like
A clear and concise description of what you want to happen.

Previous work
If work on these imports have been done, please provide links.

Need DeviceIoControlAsync expose an interface that using byte[] as input/output parameter

Is your feature request related to a problem? Please describe.

Because I need pass a struct to my kernel driver like this:

struct Model {
    public int Type;
    // must be variable array, not fixed,
    // because my data is bytes from string that describe a file path from user choose.
    // Typically, user file path have big different length.
    public byte[] Data; 
}

if I pass Model to DeviceIoControlAsync<TIn>(SafeFileHandle hDev, uint ioControlCode, TIn model), it will cause an exception, because GCHandle.Alloc not allow pin an object that contains variable array :

https://docs.microsoft.com/en-us/dotnet/framework/interop/blittable-and-non-blittable-types
The following complex types are also blittable types:
One-dimensional arrays of blittable types, such as an array of integers. However, a type that contains a variable array of blittable types is not itself blittable.

so, I change my model to this:

struct Model {
    public int Type;
    public uint DataLength;
    public IntPtr DataPtr; // this will be IntPtr.Zero until I assign it in kernel driver 

    public byte[] ToBinary(byte[] data) {
        this.DataLength = data.Length;

        var handle = GCHandle.Alloc(this, GCHandleType.Pinned);
        try {
            var size = Marshal.SizeOf(this);
            var bytes = new byte[size + DataLength];

            Marshal.Copy(handle.AddrOfPinnedObject(), bytes, 0, size);
            Buffer.BlockCopy(data, 0, bytes, size, DataLength);
 
            return bytes;

        } finally {
            handle.Free();
        }
    }
}

then I pass the new Model to DeviceIoControlAsync :

var model = new Model {  ...  };
var buffer = model.ToBinary(someBytes);
Kernel32.DeviceIoControlAsync(..., buffer);

In my driver code simply like this :

typedef struct _Model {
    int type;
    uint dataLength;
    void *data;
} Model;

...

uint length; // receive buffer length 
void *buffer = getInputBuffer(&length);
Model *model = buffer;
if (length != sizeof(Model) + model->dataLength)
    handleError();

model->data = buffer[sizeof(Model) /* skip self size, point to data*/ ];

// use model, etc ...

Virus report, maybe misinformation?

Translation:

Trojan:Win32/Cloxer.D!cl

Alert level: Serious
Status: Quarantine
DateTime: 2019/1/4 14:53
Category: Trojan Horse
Detail: This program is dangerous and executes commands from attackers.

Affected items: 
file: D:\***\packages\Vanara.PInvoke.Kernel32.2.1.0\lib\net45\Vanara.PInvoke.Kernel32.dll

image

image

CreateProcessWithTokenW has invalid signature

Describe the bug
The method CreateProcessWithTokenW in AdvApi32/.Vanara.PInvoke.Security.dll has invalid signature.

What code is involved
public static extern bool CreateProcessWithTokenW(HTOKEN hToken, ProcessLogonFlags dwLogonFlags, string lpApplicationName, [Optional] StringBuilder lpCommandLine, CREATE_PROCESS dwCreationFlags, [Optional] IntPtr lpEnvironment, [Optional] string lpCurrentDirectory, in STARTUPINFO lpStartupInfo, [Out] PROCESS_INFORMATION lpProcessInformation);

Expected behavior
According to MSDN the last parameter (LPPROCESS_INFORMATION lpProcessInformation)
should be an out parameter.
Expected: [Out] out PROCESS_INFORMATION lpProcessInformation

Screenshots
None.

Using ref structs

From readme.md:
Where structures are always passed by reference and where that structure needs to clean up memory allocations, I have changed the structure to a class implementing IDisposable.

C# 7.2 introduces reference value types which doesn't require you to use class anymore.
https://docs.microsoft.com/en-us/dotnet/csharp/reference-semantics-with-value-types

It means you don't have overhead of reference type such as GC and you keep passing arguments by reference without specifying explicitly as reference types do.
And your struct can implement IDisposable still.

Btw, 'in' keyword even allows you to pass a reference to struct which is used in 'using' unlike 'ref' keyword.

Full sample:

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp2
{
    [StructLayout(LayoutKind.Sequential)]
    public struct RECT : IDisposable
    {
        public int x, y, w, h;

        public void Dispose()
        {
            Console.WriteLine("Disposing RECT");
        }
    }

    static class User
    {
        [DllImport("user32")]
        public static extern void GetWindowRect(IntPtr a, in RECT r);

        [DllImport("user32")]
        public static extern IntPtr GetDesktopWindow();
    }

    public class Program
    {
        static void Main(string[] args)
        {
            using (var rect = new RECT())
            {
                User.GetWindowRect(User.GetDesktopWindow(), rect);
                Console.WriteLine($"{rect.w}x{rect.h}");
            }
        }
    }
}

CreateProcessand CreateProcessAsUser doesn't have IntPtr overload for security attributes

It is impossible to pass NULL value (IntPtr.Zero) to lpProcessAttributes and lpThreadAttributes parameter.

[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
		[PInvokeData("WinBase.h", MSDNShortId = "ms682425")]
		[return: MarshalAs(UnmanagedType.Bool)]
		public static extern bool CreateProcess([In] string lpApplicationName, StringBuilder lpCommandLine, [In] SECURITY_ATTRIBUTES lpProcessAttributes,
			[In] SECURITY_ATTRIBUTES lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, CREATE_PROCESS dwCreationFlags, [In] IntPtr lpEnvironment,
			[In] string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);

public static extern bool CreateProcess([In] string lpApplicationName, StringBuilder lpCommandLine, [In] SECURITY_ATTRIBUTES lpProcessAttributes,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.