Code Monkey home page Code Monkey logo

vanara's People

Contributors

5cover avatar andregleichner avatar dahall avatar gigi81 avatar greatfirewall avatar jeanbern avatar mantaspau98 avatar marklechtermann avatar martinkuschnik avatar nn--- avatar pazerop avatar peppy avatar propagating avatar psulek avatar rmeshksar avatar shirok1 avatar tajbender avatar threesevenths avatar tonyhallett avatar vessd avatar wjk avatar xh321 avatar yomodo 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  avatar

vanara's Issues

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.

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 ...

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

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

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,

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. ๐Ÿค”

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

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.

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

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.

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);

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.

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.

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}");
            }
        }
    }
}

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

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);
        }
    }
}

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

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.

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

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

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.

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.

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

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.

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)

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.

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

[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.

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?

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();
}

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.