Usage of User32.dll ToUnicodeEx function - c#

On a system with a non-US keyboard / culture, I am receiving a Barcode from a scanner as keyboard input. The scanner can be set to different cultures. In my case it is set to en-US. In this case the system language and the barcode scanner language encoding are different.
I have declared this function to decode:
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int ToUnicodeEx(uint virtualKeyCode, uint scanCode, byte[] keyboardState, [Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 4)] StringBuilder receivingBuffer, int bufferSize, uint flags, IntPtr dwhkl);
I use the method below to load a keyboard layout:
[DllImport("user32.dll")]
private static extern IntPtr LoadKeyboardLayout(string pwszKLID, uint Flags);
I use the method like below:
// loads the interpretation of the key into buf.
ToUnicodeEx(key, scankey, keyboardState, buf, 256, 0, LoadKeyboardLayout("00000409", 1));
My usage of the method works - the interpretation is correct - BUT I have a side effect that my system language setting is affected. Before method call it looks like this:
And after the method call it looks like this:
How can I fix my code so that my system's language is not affected?
I have tried to change flags parameter of the LoadKeyboardLayout to 0, but then ToUnicodeEx uses the system language, not the loaded en-US.

I'm sure that almost four years later you've either solved this or no longer care. I'll put the answer here in case someone else comes across this, though.
The last parameter of LoadKeyboardLayout is dwFlags. You gave it 1, which is equivalent to KLF_ACTIVATE, or "load this bad boy up and make it my keyboard!"
You want to call it with 0, which tells it to just load the layout, give you a handle (IntPtr) to it, and do nothing else.
I'm sorry I couldn't help you back when you posted this. :-)

Related

Using an unmanaged DLL with C#

I'm using a Silicon Labs VCP (CP2105) under Windows (7/8/10) and I am trying to obtain some info from it using the Silicon Labs runtime DLL - which is unmanaged.
This is my implementation:
[DllImport("CP210xRuntime.dll")]
private static extern Int32 CP210xRT_GetDeviceProductString(IntPtr handle, IntPtr bfPtr, ref uint len, bool convert);
public static Int32 GetProduct(IntPtr handle)
{
var buff = new char[100];
GCHandle hnd = GCHandle.Alloc(buff);
IntPtr bfPtr = (IntPtr)hnd;
uint bytesRead = 0;
var r = CP210xRT_GetDeviceProductString(handle, bfPtr, ref bytesRead, true);
hnd.Free();
return r;
}
I am getting the device handle for the ports using:
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateFile(
string FileName,
uint DesiredAccess,
uint ShareMode,
IntPtr SecurityAttributes,
uint CreationDisposition,
uint FlagsAndAttributes,
IntPtr hTemplateFile
);
When I run this it works - of sorts, that is to say the return value is 0 which, according to the Silicon Labs docs, indicates all is well, and I have confirmed this by using a handle to another device and I got 3 back, which confirms invalid handle.
The bytesRead ref value is also ammended as expected to 36 which is what the length of the product name should be. But the buff array never fills with any data (just to be sure I have written values to each element as well but they dont change). If I leave the program running the whole thing throws an exception:
Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in********
Additional information: The runtime has encountered a fatal error. The address of the error was at 0x70338780, on thread 0x1f5c. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
This is also the program does, if I comment out the line where I call the function from the dll - the program does not fail.
I'm not massively familar with invoke unmanged code using C# so if someone could help me out with where I am going wrong / point me in the right direction I would be most grateful!
This is from the Silicon Labs Docs:
CP210x_STATUS CP210xRT_GetDeviceProductString(HANDLE cyHandle, 
LPVOID lpProduct, LPBYTE lpbLength, BOOL bConvertToASCII = TRUE)

Read all text from external Application

I have a hotkey window application in C# and I want all the text from the focused window of other application on pressing hotkey like notepad, browser, command window(cmd), Turbo c++, Pascal etc.
So Is it possible?
If any one have idea please help me with code example.
I have attach screen shot. I want to read text from this window. On pressing hotkey I want to read text "This is my test text".
There is a GetWindowText() in user32 API,
but if you need to get text from a control in another process, GetWindowText() won't work.
You have to use SendMessage() with WM_GETTEXT instead:
const UInt32 WM_GETTEXT = 0x000D;
const UInt32 WM_GETTEXTLENGTH = 0x000E;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, StringBuilder lParam);
static string GetWindowTextRaw(IntPtr hwnd)
{
// Allocate string length
int length = (int)SendMessage(hwnd, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
StringBuilder sb = new StringBuilder(length + 1);
// Get window text
SendMessage(hwnd, WM_GETTEXT, (IntPtr)sb.Capacity, sb);
return sb.ToString();
}
Application that call themselves "Screen Reader" (for visually impaired people) do that kind of things, sort of.
They use the old MSSA (Microsoft Active Accessibility) APIs and/or the new UIAutomation APIs.
With the two APIs, if you have a "Main Window" HWND, you can then browse the tree of the componants making the app. You can then retrieve properties, such as "Text" or "Name" and so on.
If the application doesn't support Accessive technologies, you fall back on case by case solutions, which means eventually awful hacks (as APIs hooking) or more regular methods (as DLL injection and use of the JNI Invocation API in the JAVA case).
Its is not directly possible through C#,
Still microsoft provides with WMI services which can utilized to get at max information on the machine and processes. Kindly check MSDN
You can download WMI tool from here and possible check Win32 classes and methods, you may find useful information for your requirement

Refresh Desktop in C# on Win7 like 'F5' would have been pressed to apply explorer settings

I would like to have a function to refresh the desktop like pressing "F5" does. I found many codes with Sendmessage and ToggleDesktopIcons on/off but none worked for me like manual hit of "F5" does. I saw also some topics here, but all with non-working solutions for this matter.
I am on Windows 7 64 Bit with IE 10 and use C# Net Framework 2.
I found also this code, but C# doesn't accept it, even if it seems to me as the right function.
I dunno what I need to change here. I would expect that the IDE would tell me what is my mistake here or what I need to correct. Can someone please correct me this function or suggest another function which is compatible to C#.
procedure RefreshDesktop2;
var
hDesktop: HWND;
begin
hDesktop := FindWindowEx(FindWindowEx(FindWindow('Progman', 'Program Manager'), 0,
'SHELLDLL_DefView', ''), 0, 'SysListView32', '');
PostMessage(hDesktop, WM_KEYDOWN, VK_F5, 0);
PostMessage(hDesktop, WM_KEYUP, VK_F5, 1 shl 31);
end;
Question:
How do I make the code above working in C# (translate in C#) or how looks a similar code in C# like.
Refreshing the desktop with its icons/settings like by pressing "F5" on a selected desktop icon is my goal. Several codes which I tried in similar questions brought me no result.
OK, I don't really understand your code, in fact you have to find the exact window to send the F5 keypress to it so that it will refresh the desktop. Here is the c# code (tested and worked like a charm:)
[DllImport("user32")]
private static extern int PostMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32")]
private static extern IntPtr FindWindow(string className, string caption);
[DllImport("user32")]
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr startChild, string className, string caption);
public void RefreshDesktop(){
IntPtr d = FindWindow("Progman", "Program Manager");
d = FindWindowEx(d, IntPtr.Zero, "SHELLDLL_DefView", null);
d = FindWindowEx(d, IntPtr.Zero, "SysListView32", null);
PostMessage(d, 0x100, new IntPtr(0x74), IntPtr.Zero);//WM_KEYDOWN = 0x100 VK_F5 = 0x74
PostMessage(d, 0x101, new IntPtr(0x74), new IntPtr(1 << 31));//WM_KEYUP = 0x101
}
However I think there are still other choices for you to refresh the desktop programmatically, here is one of the links How to refresh the windows desktop programmatically (i.e. F5) from C#?

Running executable from memory

I'm trying to run an executable directly from a byte[] representation of this executable as a resource in C#.
So basically i want to run a byte[] of an PE directly without touching the harddisk.
The code I'm using for this used to work but it doesn't anymore.
The code creates a process with a frozen main thread, changes the whole process data and finally resumes it so it runs the byte[] of the PE. But it seems like the process dies if the thread is resumed, i don't really know whats wrong.
So here is the code in a pastebin because its too long for here i guess...
http://pastebin.com/18hfFvHm
EDIT:
I want to run non-managed code !
Any PE File ...
Here is some code to execute native code (inside a byte array). Note that it is not exactly what you are asking for (it's not a PE file bytes, but a native procedure bytes ie. in assembly language)
using System;
using System.Runtime.InteropServices;
namespace Native
{
class Program
{
private const UInt32 MEM_COMMIT = 0x1000;
private const UInt32 PAGE_EXECUTE_READWRITE = 0x40;
private const UInt32 MEM_RELEASE = 0x8000;
[DllImport("kernel32")] private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
[DllImport("kernel32")] private static extern bool VirtualFree(IntPtr lpAddress, UInt32 dwSize, UInt32 dwFreeType);
[DllImport("kernel32")]
private static extern IntPtr CreateThread(
UInt32 lpThreadAttributes,
UInt32 dwStackSize,
UInt32 lpStartAddress,
IntPtr param,
UInt32 dwCreationFlags,
ref UInt32 lpThreadId
);
[DllImport("kernel32")] private static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32")] private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
static void Main(string[] args)
{
byte[] nativecode = new byte[] { /* here your native bytes */ };
UInt32 funcAddr = VirtualAlloc(0, (UInt32)nativecode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Marshal.Copy(nativecode, 0, (IntPtr)(funcAddr), nativecode.Length);
IntPtr hThread = IntPtr.Zero;
UInt32 threadId = 0;
hThread = CreateThread(0, 0, funcAddr, IntPtr.Zero, 0, ref threadId);
WaitForSingleObject(hThread, 0xFFFFFFFF);
CloseHandle(hThread);
VirtualFree((IntPtr)funcAddr, 0, MEM_RELEASE);
}
}
}
This code may help:
Dynamic Process Forking of Portable Executable by Vrillon / Venus:
http://forum.gamedeception.net/threads/16557-Process-Forking-Running-Process-From-Memory
Leaving this here for everyone.
USE RUNPE
Look it up, works great :) I suggest self inject.
i found that sample, hope it will be useful for you.
http://www.cyberhackers.mybbnew.com/showthread.php?tid=178
I haven't tried this, so it's purely specutive, but I believe you want to load in into the AppDomain:
byte[] myAssm = ...
AppDomain.CurrentDomain.Load(myAssm);
AppDomain.CurrentDomain.ExecuteAssemblyByName(nameOfMyAssm);
I'm not sure if this will be much help, but here is where I answer running straight x86/x64 assembly opcodes from a C# program.
I believe your problem is that you are asking for a security hole.
To run any PE, you are asking -- "Let my secure/managed .NET app run an insecure/unmanaged app -- In a way which bypasses normal security".
Let's say I run you application (which I assume is secure). I've not given it permission to write to sensitive folder; it can't overrun buffers; it can't touch my win32 mode code. You then build, byte-by-byte, a malicious application in a byts[], and launch that. Where does Windows step in to ask me if I want to let this happen? And what does that warning say ? "Is that array of bytes from a trusted source?"
In theory, if you are running full trust, there is nothing stopping you from doing CreateProcess on rundll32.exe, unmapping rundll32.exe, and performing the initial EXE load yourself.
The way I'd go about it is inject a thread into the target process that does the work in an unmanaged way. Yes, this means piles of relocatable assembly.
The general idea is to call LdrUnloadModule to get rid of rundll32.exe, call LdrLoadModule to load the EXE, fixup the load chain to indicate it was loaded first, then restart the main thread.
Good luck to you.
Repost of Load an EXE file and run it from memory
Not tested but looks like to be the only way to do this (2nd answer)

How can I use GetNextWindow() in C#?

The Microsoft WinAPI documentation appears to suggest that user32.dll contains a function called GetNextWindow() which supposedly allows one to enumerate open windows in their Z order by calling this function repeatedly.
Pinvoke usually gives me the necessary DllImport statement to use WinAPI functions from C#. However, for GetNextWindow() it doesn't have an entry. So I tried to construct my own:
[DllImport("user32.dll")]
static extern IntPtr GetNextWindow(IntPtr hWnd, uint wCmd);
Unfortunately, when trying to call this, I get an EntryPointNotFoundException saying:
Unable to find an entry point named 'GetNextWindow' in DLL 'user32.dll'.
This seems to apply only to GetNextWindow(); other functions that are listed on Pinvoke are fine. I can call GetTopWindow() and GetWindowText() without throwing an exception.
Of course, if you can suggest a completely different way to enumerate windows in their current Z order, I'm happy to hear that too.
GetNextWindow() is actually a macro for GetWindow(), rather than an actual API method. It's for backward compatibility with the Win16 API.
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
enum GetWindow_Cmd : uint {
GW_HWNDFIRST = 0,
GW_HWNDLAST = 1,
GW_HWNDNEXT = 2,
GW_HWNDPREV = 3,
GW_OWNER = 4,
GW_CHILD = 5,
GW_ENABLEDPOPUP = 6
}
(From Pinvoke.net)
GetNextWindow is a c++ macro that calls GetWindow, so you cannot call it from .NET. Call GetWindow instead.
From MSDN:
Using this function is the same as calling the GetWindow function with the GW_HWNDNEXT or GW_HWNDPREV flag set

Categories