Extracting an icon group from a .dll file in C# - c#

I'm trying to extract an icon from imageres.dll. Specifically the "My Computer" or "This PC" icon. The problem is that at between Win7 and Win10, the icon number changes. However, the icon group does not (109). Is there a way to get that icon group, and then let the computer figure out which icon to use of that group, in the same way it figures out which icon to use for my app?
This is the code I'm using to get the specific icon via the index:
public class GetIcon {
public static Icon Extract(string file, int number) {
IntPtr large;
IntPtr small;
ExtractIconEx(file, number, out large, out small, 1);
try {
return Icon.FromHandle(small);
}
catch {
return null;
}
}
[DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons);
}
Thanks.

There are a couple of ways to do this. The most reliable, and potentially most time consuming (provided you can't find an existing library), is to parse the PE File (i.e. .exe, .dll) and extract the relevant Icon group data yourself. Here's a good resource for the format: https://msdn.microsoft.com/en-us/library/ms809762.aspx
The second way, can be done easily enough with Windows functions, however there is one caveat. It will only work on PE files that are of the same bit-type as your application. So, for example, if your application is 64-bit, it will only work on 64-bit PE files.
Here's a function I just wrote - based off this: https://msdn.microsoft.com/en-us/library/windows/desktop/ms648051(v=vs.85).aspx#_win32_Sharing_Icon_Resources, that takes a file name, group number, and desired icon size, and returns a System.Drawing.Icon
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);
[DllImport("kernel32.dll")]
static extern IntPtr FindResource(IntPtr hModule, int lpName, int lpType);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr LoadResource(IntPtr hModule, IntPtr hResInfo);
[DllImport("kernel32.dll")]
static extern IntPtr LockResource(IntPtr hResData);
[DllImport("user32.dll")]
static extern int LookupIconIdFromDirectoryEx(byte[] presbits, bool fIcon, int cxDesired, int cyDesired, uint Flags);
[DllImport("user32.dll")]
static extern IntPtr CreateIconFromResourceEx(byte[] pbIconBits, uint cbIconBits, bool fIcon, uint dwVersion, int cxDesired, int cyDesired, uint uFlags);
[DllImport("kernel32.dll", SetLastError = true)]
static extern uint SizeofResource(IntPtr hModule, IntPtr hResInfo);
const int RT_GROUP_ICON = 14;
const int RT_ICON = 0x00000003;
private System.Drawing.Icon GetIconFromGroup(string file, int groupId, int size)
{
IntPtr hExe = LoadLibrary(file);
if(hExe != IntPtr.Zero)
{
IntPtr hResource = FindResource(hExe, groupId, RT_GROUP_ICON);
IntPtr hMem = LoadResource(hExe, hResource);
IntPtr lpResourcePtr = LockResource(hMem);
uint sz = SizeofResource(hExe, hResource);
byte[] lpResource = new byte[sz];
Marshal.Copy(lpResourcePtr, lpResource, 0, (int)sz);
int nID = LookupIconIdFromDirectoryEx(lpResource, true, size, size, 0x0000);
hResource = FindResource(hExe, nID, RT_ICON);
hMem = LoadResource(hExe, hResource);
lpResourcePtr = LockResource(hMem);
sz = SizeofResource(hExe, hResource);
lpResource = new byte[sz];
Marshal.Copy(lpResourcePtr, lpResource, 0, (int)sz);
IntPtr hIcon = CreateIconFromResourceEx(lpResource, sz, true, 0x00030000, size, size, 0);
System.Drawing.Icon testIco = System.Drawing.Icon.FromHandle(hIcon);
return testIco;
}
return null;
}
The process basically works like this:
use LoadLibrary to load up the .exe or .dll file
Get the handle & data of the RT_GROUP_ICON resource
Pass the data, along with the desired size to LookupIconIdFromDirectoryEx, to get the icon index
From there, you can either use ExtractIconEx, or just repeat step 2 with the icon index, and RT_ICON instead, followed by using CreateIconFromResourceEx to get your icon handle.

Related

How to read print job content using ReadPrinter method

I'd like to get content of a document sent to printing.
Google said an only way to do that is to use WinAPI method ReadPrinter().
I've implemented a sketch but can't get it work.
A trouble is the ReadPrinter() method always returns nothing.
Please give me a hint what is wrong.
Simplified code below:
string printerName = "Microsoft XPS Document Writer";
const uint firstJob = 0u;
const uint noJobs = 10u;
const uint level = 1u;
uint bytesNeeded;
uint returned;
uint bytesCopied;
uint structsCopied;
// Open printer
IntPtr printerHandle = OpenPrinterW(printerName.Normalize(), out printerHandle, IntPtr.Zero);
// Get byte size required for a data
EnumJobsW(printerHandle, firstJob, noJobs, level, IntPtr.Zero, 0, out bytesNeeded, out returned);
// Now we know how much memory we need to read the data (bytesNeeded value)
IntPtr pJob = Marshal.AllocHGlobal((int)bytesNeeded);
// Read the data
EnumJobsW(printerHandle, firstJob, noJobs, level, pJob, bytesNeeded, out bytesCopied, out structsCopied);
// Convert pJob to jobInfos
JOB_INFO_1W[] jobInfos = null;
// ... actual convert code missed ...
// Iterate through the jobs and try to get their content
foreach (JOB_INFO_1W jobInfo in jobInfos)
{
// Open print job
string printJobName = string.Format("{0}, Job {1}", printerName, jobInfo.JobId);
IntPtr printJobHandle;
OpenPrinterW(printJobName.Normalize(), out printJobHandle, IntPtr.Zero);
// Read print job
const int printJobBufLen = 1024;
StringBuilder printJobSb = new StringBuilder(printJobBufLen);
int printJobBytesRead = 0;
while (printJobBytesRead == 0)
{
ReadPrinter(printJobHandle, printJobSb, printJobBufLen, out printJobBytesRead);
// !!! printJobBytesRead is 0 and printJobSb is empty
}
// Close print job
ClosePrinter(printJobHandle);
}
// Close printer
ClosePrinter(printerHandle);
P/Invoke signatures:
[DllImport("winspool.drv", EntryPoint = "OpenPrinterW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern int OpenPrinterW(
[In] string pPrinterName,
[Out] out IntPtr phPrinter,
[In] IntPtr pDefault);
[DllImport("spoolss.dll", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern int ClosePrinter(
[In] IntPtr hPrinter);
[DllImport("winspool.drv", EntryPoint = "EnumJobsW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern int EnumJobsW(
[In] IntPtr hPrinter,
[In] uint FirstJob,
[In] uint NoJobs,
[In] uint Level,
[Out] IntPtr pJob,
[In] uint cbBuf,
[Out] out uint pcbNeeded,
[Out] out uint pcReturned);
[DllImport("spoolss.dll", EntryPoint = "ReadPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern int ReadPrinter(
[In] IntPtr hPrinter,
[Out] StringBuilder data,
[In] Int32 cbBuf,
[Out] out Int32 pNoBytesRead);
Is this code inside a driver's Print Processor component? (Link updated to web archive.) If not, I don't think it will work.
So you either use a print driver component, or read from the spool file on disk. See here.

How do I get the "topmost" status of every window in c#

Actually I wrote my self a programm that sets the topmost status of a specific window to true or false.
I realised this by importing the user32.dll
[DllImport("user32.dll")]
private static extern bool SetWindowPos(...);
Now I was wondering if its possible to get the state of the window and see if the topmost is set and add this to the items I have in a Listview.
Of course I can do this in runtime, depending on the actions I performed, but my programm will not be opend all the time and I dont want to save data somewere.
What I want is to see in the listview if there was set topmost before and than set it true/false on buttonclick. Depending on its state...
So is there something like GetWindowPos to get the topmost state of a specific window ?
According to James Thorpe's comment I solved it like this.
First I added the needed dll and const
//Import DLL
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
//Add the needed const
const int GWL_EXSTYLE = (-20);
const UInt32 WS_EX_TOPMOST = 0x0008;
At this point i recognized that I allways have to add the DLL again when I want to use several functions of it. For example
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
I thought I can write it like
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
NOTE: You can not do it like this :D
After this I went to my function that refreshes my ListView and edited it like
//Getting the processes, running through a foreach
//...
//Inside the foreach
int dwExStyle = GetWindowLong(p.MainWindowHandle, GWL_EXSTYLE);
string isTopMost = "No";
if ((dwExStyle & WS_EX_TOPMOST) != 0)
{
isTopMost = "Yes";
}
ListViewItem wlv = new ListViewItem(isTopMost, 1);
wlv.SubItems.Add(p.Id.ToString());
wlv.SubItems.Add(p.ProcessName);
wlv.SubItems.Add(p.MainWindowTitle);
windowListView.Items.Add(wlv);
//Some sortingthings for the listview
//end of foreach processes
In this way I can display if the Window has a topmost status.

Convert C# bitmap to Windows dib handle for RIOT?

I am trying to implement an application which uses RIOT (Radical Image Optimization Tool) for batch image optimizaton. I can successfully import riot.dll into my app. But I cannot figure out how to pass a Windows DIB (Device Independent Bitmap) handle to RIOT function.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Riot_Test
{
public partial class Form1 : Form
{
[DllImport("RIOT.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
static extern bool RIOT_LoadFromDIB(IntPtr hDIB, IntPtr hwndParent, [MarshalAs(UnmanagedType.LPStr)] string fileName = "", [MarshalAs(UnmanagedType.LPStr)] string iniFile = "", int flags = 0, [MarshalAs(UnmanagedType.LPStr)] string buf = "");
[DllImport("RIOT.dll")]
static extern void RIOT_Show();
[DllImport("RIOT.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
static extern bool RIOT_LoadFromFile([MarshalAs(UnmanagedType.LPStr)] string filename, int flags = 0);
[DllImport("RIOT.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto, SetLastError = true)]
static extern bool RIOT_SaveToFile(IntPtr hDIB, IntPtr hwndParent, [MarshalAs(UnmanagedType.LPStr)] string fileName, [MarshalAs(UnmanagedType.LPStr)] string origFilename = "", ulong byteSize = 0, [MarshalAs(UnmanagedType.LPStr)] string errorText = "", int flags = 0, [MarshalAs(UnmanagedType.LPStr)] string buf = "");
public Form1()
{
InitializeComponent();
//RIOT_Show();
IntPtr hdib = IntPtr.Zero;
IntPtr hwnd = IntPtr.Zero;
string errorText = "";
Bitmap bmp = new Bitmap("dene.jpg");
hdib = bmp.GetHbitmap();
string fn = "optim2.jpg";
string fno = "dene.jpg";
bool result = RIOT_SaveToFile_U(hdib, hwnd, fn);
}
}
}
RIOT_Show() and RIOT_Load_From_File() are working as expected but when I try to call RIOT_SaveToFile() it gives me this error:
System.AccessViolationException was unhandled - Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
So my questions are:
How can I convert a System.Bitmap object to Windows DIB handle ?
If I can't convert is it possible to use a C++ library (if there is) to do the job for me and return the DIB handle?
Edit:
I've changed my code to this but it gives the same error.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace from_vb
{
public partial class Form1 : Form
{
[DllImport("gdi32.dll", SetLastError = true)]
static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll", ExactSpelling = true, PreserveSig = true, SetLastError = true)]
static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
[DllImport("gdi32.dll")]
static extern int GetObject(IntPtr hgdiobj, int cbBuffer, IntPtr lpvObject);
[DllImport("gdi32.dll")]
static extern IntPtr CreateDIBSection(IntPtr hdc, [In] ref GDI32BITMAPINFOHEADER pbmi, uint pila, out IntPtr ppvBits, IntPtr hSection, uint dwOffset);
[DllImport("gdi32.dll")]
static extern int GetDIBits(IntPtr hdc, IntPtr hbmp, uint uStartScan,
uint cScanLines, [Out] byte[] lpvBits, ref GDI32BITMAPINFOHEADER lpbmi, uint uUsage);
[DllImport("gdi32.dll")]
static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
static extern bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll")]
static extern bool GdiFlush();
[DllImport("RIOT.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto, SetLastError = true)]
static extern bool RIOT_SaveToFile(IntPtr hDIB, IntPtr hwndParent, [MarshalAs(UnmanagedType.LPStr)] string fileName, [MarshalAs(UnmanagedType.LPStr)] string origFilename = "", ulong byteSize = 0, [MarshalAs(UnmanagedType.LPStr)] string errorText = "", int flags = 0, [MarshalAs(UnmanagedType.LPStr)] string buf = "");
public const int BI_RGB = 0;
public const int DIB_PAL_COLORS = 1;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct GDI32BITMAP
{
public int bmType;
public int bmWidth;
public int bmHeight;
public int bmWidthBytes;
public short bmPlanes;
public short bmBitsPixel;
public int bmBits;
}
[StructLayout(LayoutKind.Sequential)]
public struct GDI32BITMAPINFOHEADER
{
public int biSize;
public int biWidth;
public int biHeight;
public short biPlanes;
public short biBitCount;
public int biCompression;
public int biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public uint biClrUsed;
public uint biClrImportant;
public void Init()
{
biSize = (int)Marshal.SizeOf(this);
}
}
public Form1()
{
InitializeComponent();
IntPtr hdc = IntPtr.Zero;
IntPtr hSrcBitmap = IntPtr.Zero;
IntPtr pSrcBitmapInfo = IntPtr.Zero;
IntPtr hDestDIBitmap = IntPtr.Zero;
IntPtr hDstOldBitmap = IntPtr.Zero;
IntPtr pDestDIBits = IntPtr.Zero;
IntPtr hSection = IntPtr.Zero;
IntPtr hwnd = IntPtr.Zero;
IntPtr ccDC = IntPtr.Zero;
Bitmap dotNetBitmap;
int XDPI, YDPI;
GDI32BITMAP srcBitmapInfo = new GDI32BITMAP();
//ccDC = CreateCompatibleDC(hdc);
IntPtr hDstMemDC = CreateCompatibleDC(hdc);
GDI32BITMAPINFOHEADER DestDIBMIH = new GDI32BITMAPINFOHEADER();
dotNetBitmap = new Bitmap("dene.jpg");
hSrcBitmap = dotNetBitmap.GetHbitmap();
pSrcBitmapInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(srcBitmapInfo));
GetObject(hSrcBitmap, Marshal.SizeOf(srcBitmapInfo),pSrcBitmapInfo);
srcBitmapInfo = (GDI32BITMAP)Marshal.PtrToStructure(pSrcBitmapInfo, srcBitmapInfo.GetType());
if (pSrcBitmapInfo != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pSrcBitmapInfo);
}
DestDIBMIH.biSize = Marshal.SizeOf(DestDIBMIH);
DestDIBMIH.biWidth = srcBitmapInfo.bmWidth;
DestDIBMIH.biHeight = srcBitmapInfo.bmHeight;
DestDIBMIH.biPlanes = srcBitmapInfo.bmPlanes;
DestDIBMIH.biBitCount = 24;
DestDIBMIH.biCompression = BI_RGB;
hDestDIBitmap = CreateDIBSection(hDstMemDC, ref DestDIBMIH, 0, out pDestDIBits, hSection, 0);
string fn = "optim2.jpg";
string fno = "dene.jpg";
bool hede = RIOT_SaveToFile(hDestDIBitmap, hwnd, fn);
}
}
}
Here is the "documentation" on that method:
bool RIOT_SaveToFile(HANDLE hDIB, HWND hwndParent,const char *fileName,const char *origFilename=”", unsigned long byteSize=0,char *errorText=”",int flags=0, char *buf=”")
Saves the file with the specified parameters.
Parameters:
hDIB – handle to a Windows DIB image in memory
hwndParent – Not Used. Must be NULL.
fileName – full path to the file to be saved (only JPEG is supported)
origFilename – Fill this with the original file name if the DIB is not different than the image from the file
byteSize – filesize of the compressed JPEG image in bytes
errorText – On error errorText is filled with the error message
flags – save flags. See bellow
buf – not used. Leave blank.THe function returns true on success or false on error.If you specify byteSize you can specify any of the save flags, but the quality will not be used.
If you don’t specify byteSize flags are used.
If there are no flags or byteSize is 0 an error is thrown.Flags for RIOT_SaveToFile:0×0001 – keep EXIF
0×0002 – keep IPTC
0×0004 – keep XMP
0×0008 – keep Comments
0×1000 – keep ICC profile0x0800 – save greyscale
0×2000 – save progressive
0×10000 – disable chroma subsamplingAlso you can set a quality flag from 1 to 100Ex: flags=JPEG_SUBSAMPLING_444 | JPEG_PROGRESSIVE | 90
results in a file with no subsampling, progressive with a quality of 90
If you don’t specify quality 75 is used.
You must specify JPEG_PROGRESSIVE if you want progressive.
If you don’t specify JPEG_SUBSAMPLING_444 a default chroma of 4:2:0 is used.
The first issue is with errorText. The doc states, "On error errorText is filled with the error message." This suggests that you have to pass an array of bytes of un-specified length that will get filled in. That's hideous.
The second issue is where it says, "If there are no flags or byteSize is 0 an error is thrown."
My guess is that you're getting an error and it's trying to copy bytes into errorText. Try passing a largish byte[] instead of a string.
Your System.Drawing.Bitmap object is a Device Dependent Bitmap (DDB). You need a Device Independent Bitmap (DIB). I'm not aware of any help in the .Net framework for this, but you can p/Invoke CreateDIBSection to create one.

Change file LastWriteDate in Compact Framework

FileSystemInfo.LastWriteTime property is readonly in CF.
Is there an alternative way to change that date?
P/Invoke SetFileTime.
EDIT
Something along these lines (warning: untested)
[DllImport("coredll.dll")]
private static extern bool SetFileTime(string path,
ref long creationTime,
ref long lastAccessTime,
ref long lastWriteTime);
public void SetFileTimes(string path, DateTime time)
{
var ft = time.ToFileTime();
SetFileTime(path, ref ft, ref ft, ref ft);
}
Here is a fuller implementation, adapted from the answer ctacke provides above and this StackOverflow question. I hope this proves useful to someone:
// Some Windows constants
// File access (using CreateFileW)
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint GENERIC_READ_WRITE = (GENERIC_READ + GENERIC_WRITE);
public const int INVALID_HANDLE_VALUE = -1;
// File creation (using CreateFileW)
public const int CREATE_NEW = 1;
public const int OPEN_EXISTING = 3;
// File attributes (using CreateFileW)
public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
// P/Invokes
[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr CreateFileW(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr pSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplatefile);
[DllImport("coredll.dll", SetLastError = true)]
public static extern int CloseHandle(IntPtr hObject);
// Note: Create related P/Invokes to change creation or last access time.
// This one modifies the last write time only.
[DllImport("coredll.dll", EntryPoint = "SetFileTime", SetLastError = true)]
private static extern bool SetFileWriteTime(
IntPtr hFile,
IntPtr lpCreationTimeUnused,
IntPtr lpLastAccessTimeUnused,
ref long lpLastWriteTime);
// Open a handle to the file you want changed
IntPtr hFile = CreateFileW(
path, GENERIC_READ_WRITE, 0,
IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
IntPtr.Zero);
// Modify the last write time and close the file
long lTimeNow = DateTime.Now.ToFileTime();
SetFileWriteTime(hFile, IntPtr.Zero, IntPtr.Zero, ref lTimeNow);
CloseHandle(hFile);
Note that you can use System.IO.File.GetLastWriteTime (which is exposed in the .NET Compact Framework) to read the last write time if required.

flash drive imaging

I would like to write an application that will create an 'image' of a flash drive. This includes the total topography of the drive, not just the files. So if the drive is 4GB you get a 4GB file. Is this possible, and if so, could someone point me in the direction of information on how this may be accomplished?
It is possible. I did it for an internal app, so I can't just paste the source for it, but I can give you some hints. You will have to P/Invoke some things.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", SetLastError = true)]
public static extern IntPtr CreateFile(string name, int access, int share, byte[] attributes, int create, int flags, IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int CloseHandle(IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int DeviceIoControl(IntPtr handle, DiskIoctl ioctl, byte[] inBuffer, int inBufferSize, byte[] outBuffer, int outBufferSize, ref int bytesReturned, IntPtr overlapped);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetLogicalDriveStringsW", SetLastError = true)]
public static extern int GetLogicalDriveStrings(int bufferLength, byte[] buffer);
public enum DiskIoctl
{
ScsiPassThrough = 315396,
Lock = 589848,
Unlock = 589852,
Dismount = 589856,
UpdateProperties = 459072,
GetDiskLayout = 475148,
SetDiskLayout = 507920
}
public enum ScsiOp
{
ReadCapacity = 0x25,
Read = 0x28,
Write = 0x2A
}
Have you tried simply opening the drive as a file and copying it?

Categories

Resources