How to use ESC/POS command with C#? I need format like this
but I cannot achieve this format.
I tried some codes ,but no use.
using (var ms = new MemoryStream())
using (var bw = new BinaryWriter(ms))
{
// Reset the printer bws (NV images are not cleared)
bw.Write(AsciiControlChars.Escape);
bw.Write('#');
bw.Write(AsciiControlChars.Newline);
bw.Write(AsciiControlChars.Escape);
bw.Write("_______________________________________________");
bw.Write(AsciiControlChars.Newline);
bw.Write("Service Price Qty Total");
bw.Write("------------------------------------------------");
bw.Write(AsciiControlChars.GroupSeparator);
bw.Write('V');
bw.Write((byte)66);
bw.Write((byte)3);
bw.Flush();
// Send the converted ANSI string to the printer.
}
You can check this link. I now using that and It's Works!!
http://www.codeproject.com/Tips/704989/Print-Direct-To-Windows-Printer-EPOS-Receipt
Use with careful, you must know ESC/POS command for thermal printer. If I'm not mistaken, the manual command must exit on the CD that came with the printer.
Kind Regards
Bonus:
http://www.developerfusion.com/tools/convert/vb-to-csharp/
I know that this is not exactly an answer to the question of how to use escape codes, but it would be much better to create a PDF file (P for Portable). You'll have a better chance to have it rendered exactly as intended on most printers.
You can generate a PDF with PDFsharp. It's open source and free and it's quite simple to use.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace Apteka.Printer
{
public class RawPrinterHelper
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)]
public string pDocName;
[MarshalAs(UnmanagedType.LPStr)]
public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)]
public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, ref IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In()][MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, ref Int32 dwWritten);
private IntPtr hPrinter = new IntPtr(0);
private DOCINFOA di = new DOCINFOA();
private bool PrinterOpen = false;
public bool PrinterIsOpen
{
get
{
return PrinterOpen;
}
}
public bool OpenPrint(string szPrinterName)
{
if (PrinterOpen == false)
{
di.pDocName = ".NET RAW Document";
di.pDataType = "RAW";
if (OpenPrinter(szPrinterName.Normalize(), ref hPrinter, IntPtr.Zero))
{
if (StartDocPrinter(hPrinter, 1, di))
{
if (StartPagePrinter(hPrinter))
PrinterOpen = true;
}
}
}
return PrinterOpen;
}
public void ClosePrint()
{
if (PrinterOpen)
{
EndPagePrinter(hPrinter);
EndDocPrinter(hPrinter);
ClosePrinter(hPrinter);
PrinterOpen = false;
}
}
public bool SendStringToPrinter(string szPrinterName, string szString)
{
if (PrinterOpen)
{
IntPtr pBytes;
Int32 dwCount;
Int32 dwWritten = 0;
dwCount = szString.Length;
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
var res= WritePrinter(hPrinter, pBytes, dwCount, ref dwWritten);
Marshal.FreeCoTaskMem(pBytes);
return res;
}
else
return false;
}
}
}
I was working on thermal printer and I came across to ESC/POS commands like you do.After Googling I found ThermalDotNet very useful for me.This class also supports image printing as well as letter printing.
I hope this helps ;)
Related
I have windows service where I send PDF document for printing. The document is formed correctly and normally opens in Adobe PDF. However, if I send it to print, then it is displayed incorrectly (see attachments). At the same time, it is also normal in the print queue (spool). What could be the problem ? My code is below
namespace PrintTicketWcfModule
{
class Print
{
public bool PrintData(byte[] data)
{
return RawPrinterHelper.SendFileToPrinter(data);
}
}
}
namespace PrintPdfFile
{
public class RawPrinterHelper
{
// Structure and API declarions:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)]
public string pDocName;
[MarshalAs(UnmanagedType.LPStr)]
public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)]
public string pDataType;
}
#region dll Wrappers
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
[DllImport("winspool.Drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool GetDefaultPrinter(StringBuilder pszBuffer, ref int size);
#endregion dll Wrappers
#region Methods
/// <summary>
/// This function gets the pdf file name.
/// This function opens the pdf file, gets all its bytes & send them to print.
/// </summary>
/// <param name="szPrinterName">Printer Name</param>
/// <param name="szFileName">Pdf File Name</param>
/// <returns>true on success, false on failure</returns>
public static bool SendFileToPrinter(byte [] bytes)
{
try
{
#region Get Connected Printer Name
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PrinterResolution.Kind = PrinterResolutionKind.Medium;
PaperSize paperSize = pd.PrinterSettings.PaperSizes.OfType<PaperSize>().FirstOrDefault(x=>x.Kind == PaperKind.A4);
if (paperSize != null)
pd.DefaultPageSettings.PaperSize = paperSize;
StringBuilder dp = new StringBuilder(256);
int size = dp.Capacity;
if (GetDefaultPrinter(dp, ref size))
{
Logger.Log.Info("GetDefaultPrnt");
pd.PrinterSettings.PrinterName = dp.ToString().Trim();
}
else
{
pd.PrinterSettings.PrinterName = ConfigurationManager.AppSettings["printerName"];
}
#endregion Get Connected Printer Name
Logger.Log.Info("DafaultPrtn = " + pd.PrinterSettings.PrinterName);
bool success = false;
// Unmanaged pointer.
IntPtr ptrUnmanagedBytes = new IntPtr(0);
int nLength = bytes.Length;
Logger.Log.Info("ByteLenght = " + nLength);
ptrUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, ptrUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
Logger.Log.Info("SendTaskToPrnt");
success = SendBytesToPrinter(pd.PrinterSettings.PrinterName, ptrUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(ptrUnmanagedBytes);
return success;
}
catch (Exception ex)
{
Logger.Log.Error(ex);
return false;
}
}
/// <summary>
/// This function gets the printer name and an unmanaged array of bytes, the function sends those bytes to the print queue.
/// </summary>
/// <param name="szPrinterName">Printer Name</param>
/// <param name="pBytes">No. of bytes in the pdf file</param>
/// <param name="dwCount">Word count</param>
/// <returns>True on success, false on failure</returns>
private static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
try
{
Logger.Log.Info("Start Print");
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool success = false; // Assume failure unless you specifically succeed.
di.pDocName = "PDF Document";
di.pDataType = "RAW";
// Open the printer.
if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
{
Logger.Log.Info("OpenPrinter");
// Start a document.
if (StartDocPrinter(hPrinter, 1, di))
{
Logger.Log.Info("StartDocPrinter");
// Start a page.
if (StartPagePrinter(hPrinter))
{
Logger.Log.Info("StartPagePrinter");
// Write the bytes.
success = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If print did not succeed, GetLastError may give more information about the failure.
if (success == false)
{
dwError = Marshal.GetLastWin32Error();
}
return success;
}
catch (Exception ex)
{
Logger.Log.Error(ex);
throw new Exception(ex.Message);
}
}
#endregion Methods
}
}
Windows 10 supports custom locales, locales that do not have an LCID like older locales from older versions of Windows. In each update to Windows 10, Microsoft has been adding lesser used locales for minority and indigenous languages.
A recent update to Windows 10 added the the Võro kiil (vro) locale. When using EnumSystemLocalesEx to enumerate all supported locales, vro does not appear in any form. However, in the system settings UI for adding a new language or keyboard, Võro kiil does appear.
However, if the user then enables this language, when you call EnumSystemLocalesEx, vro, vro-Latn and vro-Latn-001 are now listed. If the user then removes this locale from the UI, it no longer appears in the results of this function call.
The question: is there a way (supported or otherwise) to get a list of all the known locales to the operating system regardless of whether the user has enabled them or not?
I find it very bizarre that this output includes other minority languages like Skolt Sami without requiring the user to enable it in advance.
I will quite happily accept an answer that uses the .NET framework if the API does not exist in the C/C++ APIs, so long as I can actually get this data.
Example code to generate the locale output:
#include <cstdio>
#include "stdafx.h"
#include "windows.h"
BOOL CALLBACK Callback(LPWSTR pStr, DWORD dwFlags, LPARAM lparam)
{
wprintf(L"%ls\n", pStr);
return TRUE;
}
int main()
{
EnumSystemLocalesEx(Callback, 0, 0, 0);
return 0;
}
With Võro kiil enabled from the "Region and Language" screen in System Settings, the final three results are vro-Latn, vro-Latn-001 and vro. When not enabled, they do not appear in the output at all.
Using .NET APIs seems to have the same behaviour.
#include "stdafx.h"
using namespace System;
using namespace System::Globalization;
int main()
{
System::Collections::IEnumerator^ enum0 = CultureInfo::GetCultures(CultureTypes::AllCultures)->GetEnumerator();
while (enum0->MoveNext())
{
CultureInfo^ ci = safe_cast<CultureInfo^>(enum0->Current);
Console::WriteLine("{0}", ci->Name);
}
}
In effect, the new language model for Windows means that there is no "list" beyond those that have historical LCIDs.
The Windows 8.1 and 10 settings tools link to bcp47langs.dll and winlangdb.dll, which provide functions for enabling languages and input methods so long as the provided input is a valid ISO 639-3 language code.
In some cases, if you want your language to appear in the UI or via these APIs, you must provide at least the script and sometimes the region. An example is myv-Cyrl for the Erzya language.
Using these APIs
Using an MSIL disassembler on a cmdlet bundled with PowerShell, I found a p/invoke definition that has allowed me to successfully use these APIs from C# and Rust code.
Here it is, for posterity:
// Decompiled with JetBrains decompiler
// Type: Microsoft.InternationalSettings.Commands.LPAPIWrapper
// Assembly: Microsoft.InternationalSettings.Commands, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// MVID: E0B49792-544F-4FBD-8C35-D4DA177385AF
// Assembly location: C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.InternationalSettings.Commands\v4.0_3.0.0.0__31bf3856ad364e35\Microsoft.InternationalSettings.Commands.dll
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Microsoft.InternationalSettings.Commands
{
internal class LPAPIWrapper
{
public static uint GEO_NATION = 1;
public static uint GEO_FRIENDLYNAME = 8;
public static uint GEOCLASS_NATION = 16;
public static uint GEOCLASS_REGION = 14;
[DllImport("kernelbase.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int NlsUpdateLocale(string LocaleName, int Flags);
[DllImport("intl.cpl", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int IntlUpdateSystemLocale(string LocaleName, int dwFlags);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int SystemParametersInfo(
uint Action,
uint UnsignedParam,
IntPtr Param,
uint WinIni);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int SendNotifyMessage(
IntPtr wWwnd,
uint Msg,
IntPtr wParam,
string lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetSystemDefaultLocaleName(
StringBuilder LocaleName,
int LocaleNameSize);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetUserGeoID(uint GeoClass);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int SetUserGeoID(int GeoId);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetGeoInfo(
int Location,
uint GeoType,
StringBuilder GeoData,
int Length,
ushort LangID);
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetUserLanguages(char Delimiter, [MarshalAs(UnmanagedType.HString)] ref string UserLanguages);
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetUserLanguageInputMethods(
string Language,
char Delimiter,
[MarshalAs(UnmanagedType.HString)] ref string InputMethods);
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int LcidFromBcp47([MarshalAs(UnmanagedType.HString)] string LanguageTag, ref int Lcid);
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetPendingUserDisplayLanguage([MarshalAs(UnmanagedType.HString)] ref string language);
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetUserDisplayLanguageOverride([MarshalAs(UnmanagedType.HString)] ref string language);
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int SetUserDisplayLanguageOverride(string LanguageTag);
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int ClearUserDisplayLanguageOverride();
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetHttpAcceptLanguageOptOut(ref bool IsOptOut);
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int SetHttpAcceptLanguageOptOut();
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int ClearHttpAcceptLanguageOptOut();
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetUserLocaleFromLanguageProfileOptOut(ref bool IsOptOut);
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int SetUserLocaleFromLanguageProfileOptOut();
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int ClearUserLocaleFromLanguageProfileOptOut();
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int RemoveInputsForAllLanguagesInternal();
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int SetInputMethodOverride(string TipString);
[DllImport("bcp47langs.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int Bcp47GetIsoLanguageCode([MarshalAs(UnmanagedType.HString)] string languageTag, [MarshalAs(UnmanagedType.HString)] ref string isoLanguageCode);
[DllImport("ext-ms-win-globalization-input-l1-1-2.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int WGIGetDefaultInputMethodForLanguage(
[MarshalAs(UnmanagedType.HString)] string Language,
[MarshalAs(UnmanagedType.HString)] ref string DefaultTipString);
[DllImport("ext-ms-win-globalization-input-l1-1-2.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int WGITransformInputMethodsForLanguage(
[MarshalAs(UnmanagedType.HString)] string TipString,
[MarshalAs(UnmanagedType.HString)] string Language,
[MarshalAs(UnmanagedType.HString)] ref string TransformedTipString);
[DllImport("winlangdb.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int SetUserLanguages(char Delimiter, [MarshalAs(UnmanagedType.HString)] string UserLanguages);
[DllImport("winlangdb.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetLanguageNames(
string Language,
StringBuilder Autonym,
StringBuilder EnglishName,
StringBuilder LocalName,
StringBuilder ScriptName);
[DllImport("ext-ms-win-globalization-input-l1-1-2.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int WGIIsImeInputMethod([MarshalAs(UnmanagedType.HString)] string TipString, ref int result);
[DllImport("winlangdb.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int EnsureLanguageProfileExists();
[DllImport("input.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int InstallLayoutOrTip(string TipString, int Flags);
[DllImport("input.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int SetDefaultLayoutOrTip(string TipString, int Flags);
[DllImport("input.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetLayoutDescription(
string LayoutId,
StringBuilder LayoutDescription,
ref int DescriptionLength);
private LPAPIWrapper()
{
}
}
}
I am using VS2010. .NET Framework 3.5.
Pre-conditions:
Adobe is not installed on the system.
3rd party dlls not to be used
Windows dlls should be used.
So far, I am able to print a pdf file, but not able to change printer setting at run time.
The basic thought for printing pdf file is that, I read bytes of pdf file and directly send them to printer. Here it prints the pdf file without any problem.
But the file is printing side by side on a page, but I want it to print only one side of the page not the both sides. For that I am trying to change printer setting at run time.
I have tested my code on two different printers. On one printer it is printing side by side of the same page and on another printer on one page only. That means, printer settings is not getting changed.
Code is as shown below. Used 4 classes:
//Class 1: This class basically tries to change the printer setting at run time
public class PrinterSettingForPdf
{
#region "Private Variables"
private IntPtr hPrinter = new System.IntPtr();
private PRINTER_DEFAULTS PrinterValues = new PRINTER_DEFAULTS();
private PRINTER_INFO_2 pinfo = new PRINTER_INFO_2();
//private PRINTER_INFO_9 pinfo9 = new PRINTER_INFO_9();
private DEVMODE dm;
private IntPtr ptrDM;
private IntPtr ptrPrinterInfo;
private int sizeOfDevMode = 0;
private int lastError;
private int nBytesNeeded;
private long nRet;
private int intError;
private System.Int32 nJunk;
private IntPtr yDevModeData;
#endregion
#region "Constants"
private const int DM_DUPLEX = 0x1000;
private const int DM_IN_BUFFER = 8;
private const int DM_OUT_BUFFER = 2;
private const int PRINTER_ACCESS_ADMINISTER = 0x4;
private const int PRINTER_ACCESS_USE = 0x8;
private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
private const int PRINTER_ALL_ACCESS =
(STANDARD_RIGHTS_REQUIRED | PRINTER_ACCESS_ADMINISTER
| PRINTER_ACCESS_USE);
#endregion
#region "Win API Def"
[DllImport("kernel32.dll", EntryPoint = "GetLastError", SetLastError = false,
ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern Int32 GetLastError();
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true,
ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesA", SetLastError = true,
ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter,
[MarshalAs(UnmanagedType.LPStr)] string pDeviceNameg,
IntPtr pDevModeOutput, ref IntPtr pDevModeInput, int fMode);
[DllImport("winspool.Drv", EntryPoint = "GetPrinterA", SetLastError = true,
CharSet = CharSet.Ansi, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
private static extern bool GetPrinter(IntPtr hPrinter, Int32 dwLevel,
IntPtr pPrinter, Int32 dwBuf, out Int32 dwNeeded);
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA",
SetLastError = true, CharSet = CharSet.Ansi,
ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool
OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter,
out IntPtr hPrinter, ref PRINTER_DEFAULTS pd);
[DllImport("winspool.drv", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern bool SetPrinter(IntPtr hPrinter, int Level, IntPtr
pPrinter, int Command);
#endregion
#region "Data structure"
[StructLayout(LayoutKind.Sequential)]
public struct PRINTER_DEFAULTS
{
public int pDatatype;
public int pDevMode;
public int DesiredAccess;
}
[StructLayout(LayoutKind.Sequential)]
private struct PRINTER_INFO_2
{
[MarshalAs(UnmanagedType.LPStr)]
public string pServerName;
[MarshalAs(UnmanagedType.LPStr)]
public string pPrinterName;
[MarshalAs(UnmanagedType.LPStr)]
public string pShareName;
[MarshalAs(UnmanagedType.LPStr)]
public string pPortName;
[MarshalAs(UnmanagedType.LPStr)]
public string pDriverName;
[MarshalAs(UnmanagedType.LPStr)]
public string pComment;
[MarshalAs(UnmanagedType.LPStr)]
public string pLocation;
public IntPtr pDevMode;
[MarshalAs(UnmanagedType.LPStr)]
public string pSepFile;
[MarshalAs(UnmanagedType.LPStr)]
public string pPrintProcessor;
[MarshalAs(UnmanagedType.LPStr)]
public string pDatatype;
[MarshalAs(UnmanagedType.LPStr)]
public string pParameters;
public IntPtr pSecurityDescriptor;
public Int32 Attributes;
public Int32 Priority;
public Int32 DefaultPriority;
public Int32 StartTime;
public Int32 UntilTime;
public Int32 Status;
public Int32 cJobs;
public Int32 AveragePPM;
}
/// <summary>
/// The PRINTER_INFO_9 structure specifies the per-user default printer settings.
/// </summary>
/// <seealso href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd162852(v=vs.85).aspx"/>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal class PRINTER_INFO_9
{
/// <summary>
/// A pointer to a DEVMODE structure that defines the per-user
/// default printer data such as the paper orientation and the resolution.
/// The DEVMODE is stored in the user's registry.
/// </summary>
public IntPtr pDevMode;
}
private const short CCDEVICENAME = 32;
private const short CCFORMNAME = 32;
[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCDEVICENAME)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public short dmOrientation;
public short dmPaperSize;
public short dmPaperLength;
public short dmPaperWidth;
public short dmScale;
public short dmCopies;
public short dmDefaultSource;
public short dmPrintQuality;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCFORMNAME)]
public string dmFormName;
public short dmUnusedPadding;
public short dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
}
#endregion
#region "Function to change printer settings"
public bool ChangePrintersetting(string sPrinterName, PrinterData pd, int numbeOfCopies, bool preserverOldSettings)
{
if (((int)pd.Duplex < 1) || ((int)pd.Duplex > 3))
{
throw new ArgumentOutOfRangeException("nDuplexSetting", "nDup lexSetting is incorrect.");
}
else
{
const int PRINTER_ACCESS_ADMINISTER = 0x4;
const int PRINTER_ACCESS_USE = 0x8;
const int PRINTER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE);
//const int READ_CONTROL = 0x20000;
//const int PRINTER_NORMAL_ACCESS = 131080; // (READ_CONTROL | PRINTER_ACCESS_USE);
PrinterValues.pDatatype = 0;
PrinterValues.pDevMode = 0;
PrinterValues.DesiredAccess = PRINTER_ALL_ACCESS;
nRet = Convert.ToInt32(OpenPrinter(sPrinterName, out hPrinter, ref PrinterValues));
if (nRet == 0)
{
lastError = Marshal.GetLastWin32Error();
throw new Win32Exception(Marshal.GetLastWin32Error());
}
GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out nBytesNeeded);
if (nBytesNeeded <= 0)
{
return false;
}
// Allocate enough space for PRINTER_INFO_2...
//ptrPrinterInfo = Marshal.AllocCoTaskMem(nBytesNeeded);
ptrPrinterInfo = Marshal.AllocHGlobal(nBytesNeeded);
// The second GetPrinter fills in all the current settings, so all you
// need to do is modify what you're interested in...
nRet = Convert.ToInt32(GetPrinter(hPrinter, 2, ptrPrinterInfo, nBytesNeeded, out nJunk));
if (nRet == 0)
{
lastError = Marshal.GetLastWin32Error();
throw new Win32Exception(Marshal.GetLastWin32Error());
}
pinfo = (PRINTER_INFO_2)Marshal.PtrToStructure(ptrPrinterInfo, typeof(PRINTER_INFO_2));
IntPtr Temp = new IntPtr();
int i1 = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, IntPtr.Zero, ref Temp, 0);
//IntPtr yDevModeData = Marshal.AllocCoTaskMem(i1);
IntPtr yDevModeData = Marshal.AllocHGlobal(i1);
i1 = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, yDevModeData, ref Temp, 2);
dm = (DEVMODE)Marshal.PtrToStructure(yDevModeData, typeof(DEVMODE));
dm.dmDefaultSource = (short)pd.Source;
dm.dmOrientation = (short)pd.Orientation;
dm.dmPaperSize = (short)pd.Size;
dm.dmCopies = (short)1;
dm.dmDuplex = (short)pd.Duplex;
Marshal.StructureToPtr(dm, yDevModeData, true);
//nRet = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, yDevModeData
// , ref yDevModeData, (DM_IN_BUFFER | DM_OUT_BUFFER));
if ((nRet == 0) || (hPrinter == IntPtr.Zero))
{
lastError = Marshal.GetLastWin32Error();
//string myErrMsg = GetErrorMessage(lastError);
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (pinfo.pDevMode == IntPtr.Zero)
{
// If GetPrinter didn't fill in the DEVMODE, try to get it by calling
// DocumentProperties...
IntPtr ptrZero = IntPtr.Zero;
//get the size of the devmode structure
sizeOfDevMode = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, ptrZero, ref ptrZero, 0);
if (nRet <= 0)
{
return false;
}
ptrDM = Marshal.AllocCoTaskMem(sizeOfDevMode);
int i;
i = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, ptrDM,
ref ptrZero, DM_OUT_BUFFER);
if ((i < 0) || (ptrDM == IntPtr.Zero))
{
//Cannot get the DEVMODE structure.
return false;
}
pinfo.pDevMode = ptrDM;
}
if (!Convert.ToBoolean(dm.dmFields & DM_DUPLEX))
{
//You cannot modify the duplex flag for this printer
//because it does not support duplex or the driver does not support setting
//it from the Windows API.
//return false;
}
pinfo.pDevMode = yDevModeData;
pinfo.pSecurityDescriptor = IntPtr.Zero;
/*update driver dependent part of the DEVMODE
i1 = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, yDevModeData
, ref pinfo.pDevMode, (DM_IN_BUFFER | DM_OUT_BUFFER));*/
if (i1 < 0)
{
//Unable to set duplex setting to this printer.
return false;
}
Marshal.StructureToPtr(pinfo, ptrPrinterInfo, true);
lastError = Marshal.GetLastWin32Error();
nRet = Convert.ToInt16(SetPrinter(hPrinter, 2, ptrPrinterInfo, 0));
if (nRet == 0)
{
//Unable to set shared printer settings.
lastError = Marshal.GetLastWin32Error();
//string myErrMsg = GetErrorMessage(lastError);
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return Convert.ToBoolean(nRet);
}
}
#endregion
}
//Class 2: Supporting Printer setting class
public class PrinterData
{
public int Duplex { get; set; }
public int Source { get; set; }
public int Orientation { get; set; }
public int Size { get; set; }
}
//Class 3: This class uses Windows dlls methods to print pdf contents
public class PrintPdf
{
// Structure and API declarions:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)]
public string pDocName;
[MarshalAs(UnmanagedType.LPStr)]
public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)]
public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "My C#.NET RAW Document";
di.pDataType = "RAW";
// Open the printer.
//if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
PrinterSettingForPdf objPS = new PrinterSettingForPdf();
PrinterData objPD = new PrinterData();
objPD.Duplex = 1;
objPD.Orientation = 1;
//objPD.Size = 1;
//objPD.Source = 1;
if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
{
// Start a document.
if (StartDocPrinter(hPrinter, 1, di))
{
// Start a page.
if (StartPagePrinter(hPrinter))
{
objPS.ChangePrintersetting(szPrinterName, objPD, 1, false);
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
if (hPrinter != IntPtr.Zero)
ClosePrinter(hPrinter);
// ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if (bSuccess == false)
{
dwError = Marshal.GetLastWin32Error();
}
return bSuccess;
}
public static bool SendFileToPrinter(string szPrinterName, string szFileName)
{
// Open the file.
FileStream fs = new FileStream(szFileName, FileMode.Open);
// Create a BinaryReader on the file.
BinaryReader br = new BinaryReader(fs);
// Dim an array of bytes big enough to hold the file's contents.
Byte[] bytes = new Byte[fs.Length];
bool bSuccess = false;
// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);
int nLength;
nLength = Convert.ToInt32(fs.Length);
// Read the contents of the file into the array.
bytes = br.ReadBytes(nLength);
// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return bSuccess;
}
public static bool SendStringToPrinter(string szPrinterName, string szString)
{
IntPtr pBytes;
Int32 dwCount;
// How many characters are in the string?
dwCount = szString.Length;
// Assume that the printer is expecting ANSI text, and then convert
// the string to ANSI text.
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
// Send the converted ANSI string to the printer.
SendBytesToPrinter(szPrinterName, pBytes, dwCount);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
}
//Class 4: Class that handles printing pdf
public class PrintingPDFData
{
public void SilentPrintPdf(string PdfFileName, string PrinterName)
{
try
{
PrintPdf.SendFileToPrinter(PrinterName, PdfFileName);
}
catch (Exception ex)
{
}
}
}
Please let me know, if any further clarification is needed.
Thanks in advance.
I believe the device mode settings are unavailable when printing a high-level document using the Win32 winspool API (if I am interpreting the documentation correctly). According to MSDN:
The DEVMODE settings defined in the PRINTER_DEFAULTS structure of the pDefault parameter are not used when the value of the pDatatype member of the DOC_INFO_1 structure that was passed in the pDocInfo parameter of the StartDocPrinter call is "RAW". When a high-level document (such as an Adobe PDF or Microsoft Word file) or other printer data (such PCL, PS, or HPGL) is sent directly to a printer with pDatatype set to "RAW", the document must fully describe the DEVMODE-style print job settings in the language understood by the hardware.
https://msdn.microsoft.com/en-us/library/windows/desktop/dd162751%28v=vs.85%29.aspx
You are using "RAW" to send your PDF bytes to the printer, which is the scenario described here.
I am using sharedmemory in my c# app with c++ interop. Currently I am marshalling a struct to a pointer and broadcasting the message. The program I am broadcasting to, opens up correctly with the debug message, but doesn't show/bring-in the data that I had in use within my struct.
Thanks!
The app I am trying to talk to was written in c++ and I am coding in c#. I am using all the DLLImports correctly (I think) and it compiles and runs error free.
using System.Runtime.InteropServices;
[DllImport("user32", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public static extern uint RegisterWindowMessageW([In]string lpString);
[DllImport("user32", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern uint RegisterWindowMessageA([In]string lpString);
[DllImport("kernel32", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
public static extern IntPtr OpenFileMapping(FileMapAccessRights dwDesiredAccess, int bInheritHandle, [In]String lpName);
[DllImport("kernel32", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
public static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, FileMapAccessRights dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, UIntPtr dwNumberOfBytesToMap);
[DllImport("kernel32", CallingConvention = CallingConvention.StdCall)]
public static extern int UnmapViewOfFile(IntPtr lpBaseAddress);
[DllImport("kernel32", CallingConvention = CallingConvention.StdCall)]
public static extern int CloseHandle(IntPtr hObject);
[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
uint WM_ZOOM_XYZ = RegisterWindowMessageA("WM_ZOOM_XYZ");
int i = Broadcast_Zoom_Message(10000, 10000, 0, WM_ZOOM_XYZ);
public int Broadcast_Zoom_Message(double dbX, double dbY, double dbZ, uint uMessage)
{
string smSharedMemory = "COORDINATES";
IntPtr hMem = OpenFileMapping(FileMapAccessRights.Write, FALSE, smSharedMemory);
if (IntPtr.Zero == hMem)
{
return 0;
}
IntPtr pvHead = MapViewOfFile(hMem, FileMapAccessRights.Write, 0, 0, UIntPtr.Zero);
if (IntPtr.Zero == pvHead)
{
CloseHandle(hMem);
MessageBox.Show(
"Unable to view " + smSharedMemory,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return 0;
}
CoordinatesStruct structCoords = new CoordinatesStruct();
Marshal.PtrToStructure(pvHead, structCoords);
int bVersionOk = FALSE;
if (1 == structCoords.uMajorVersion)
{
if (WM_ZOOM_XYZ == uMessage)
{
structCoords.dbDesiredX = dbX;
structCoords.dbDesiredY = dbY;
structCoords.dbDesiredZ = dbZ;
}
bVersionOk = TRUE;
}
else
{
MessageBox.Show(
"Unrecognized shared memory: " +
structCoords.uMajorVersion.ToString() + "." + structCoords.uMinorVersion.ToString());
}
if (IntPtr.Zero != hMem)
{
CloseHandle(hMem);
}
UnmapViewOfFile(pvHead);
IntPtr HWND_BROADCAST = (IntPtr)0xffff;
if (bVersionOk == TRUE)
{
PostMessage(HWND_BROADCAST, uMessage, 0, 0);
return 1;
}
else
return 0;
}
I think your intention was to put the changed structCoords back to the mapped file. When we use Marshal.PtrToStructure() we receive a copy of the content of the unmanaged memory. The changes of the received object will not reflect in the unmanaged memory. When we are done with the data, we should put the changes back to the memory using Marshal.StructureToPtr.
Here is what I think it should be:
if (1 == structCoords.uMajorVersion)
{
if (WM_ZOOM_XYZ == uMessage)
{
structCoords.dbDesiredX = dbX;
structCoords.dbDesiredY = dbY;
structCoords.dbDesiredZ = dbZ;
}
bVersionOk = TRUE;
Marshal.StructureToPtr(structCoords , pvHead, false); // <-- this is what you (I) forgot!
}
I would like to add a string resource to an executable file programmatically. Just for example purposes, let's say I am trying to add a string named "String SO" which holds the value of "stringVal"
If this helps anyone - if I were to do this through VS.net I could just right click on my Project => Resources => Add New String Resource etc..
I am using the following Win32 API's:
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr BeginUpdateResource(string pFileName,
[MarshalAs(UnmanagedType.Bool)]bool bDeleteExistingResources);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool UpdateResource(IntPtr hUpdate, uint lpType, uint lpName, ushort wLanguage, byte[] lpData, uint cbData);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool EndUpdateResource(IntPtr hUpdate, bool fDiscard);
So, I have found a couple of pages online but none of them seem to help me in what I am trying to do. If any of you are able to find anything I would be very grateful.
Otherwise, I would greatly appreciate any snippets that may help.
Thank you,
Evan
There is a very helpful library for many resource-tasks at github.
Many classes and function do wrap those window-api-calls around UpdateResource(...), etc.
Hope that helps.
I'm injecting an application byte[] as a resource to execute it on runtime. Here's my piece of code, hope it helps:
class AddResource
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool UpdateResource(IntPtr hUpdate, string lpType, string lpName, ushort wLanguage, IntPtr lpData, uint cbData);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr BeginUpdateResource(string pFileName,
[MarshalAs(UnmanagedType.Bool)]bool bDeleteExistingResources);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool EndUpdateResource(IntPtr hUpdate, bool fDiscard);
private static IntPtr ToPtr(object data)
{
GCHandle h = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr ptr;
try
{
ptr = h.AddrOfPinnedObject();
}
finally
{
h.Free();
}
return ptr;
}
public static bool InjectResource(string filename, byte[] bytes, string resourceName)
{
try
{
IntPtr handle = BeginUpdateResource(filename, false);
byte[] file1 = bytes;
IntPtr fileptr = ToPtr(file1);
bool res = UpdateResource(handle, resourceName,
//"RT_RCDATA",
"0", 0, fileptr, Convert.ToUInt32(file1.Length));
EndUpdateResource(handle, false);
}
catch
{
return false;
}
return true;
}
public static void CopyStream(Stream input, Stream output,long sz)
{
// Insert null checking here for production
byte[] buffer = new byte[sz];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
Here is how I use it:
using (Stream input = Assembly.GetExecutingAssembly().GetManifestResourceStream("AppLicensing.Resources.SAppStarter.exe"))
using (Stream output = File.Create(outputFilePath))
{
long sz = input.Length;
AddResource.CopyStream(input, output, sz);
}
//inject crypted bytes
AddResource.InjectResource(outputFilePath, Encryptor.cryptedbytes, "RT_RCDATA");
And here is how I extract the resource (notice the "RT_RCDATA" -> that s the name of the resource):
class ReadResource
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr FindResource(IntPtr hModule, string lpName, string lpType);
[DllImport("Kernel32.dll", EntryPoint = "SizeofResource", SetLastError = true)]
private static extern uint SizeofResource(IntPtr hModule, IntPtr hResource);
[DllImport("Kernel32.dll", EntryPoint = "LoadResource", SetLastError = true)]
private static extern IntPtr LoadResource(IntPtr hModule, IntPtr hResource);
public static byte[] GetFromResource(String resourceName)
{
try
{
IntPtr hModule = GetModuleHandle(System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName);
IntPtr loc = FindResource(hModule, "0", resourceName);
uint size = SizeofResource(hModule, loc);
IntPtr x = LoadResource(hModule, loc);
byte[] bPtr = new byte[size];
Marshal.Copy(x, bPtr, 0, (int)(size));
return bPtr;
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
System.Environment.Exit(0);
return null;
}
}
}
byte[] encryptedData = ReadResource.GetFromResource("RT_RCDATA");
The code gets a bit messy... hope this helps.
Although the author is dealing with his own issue right now, the SO question UpdateResource function fails has code snippet for using these calls.
The code from Samson work with String lpType, that mean you can't actually add RT_RCDATA resource either reading from it, it's only create and read lpType named "RT_RCDATA" only. If you want it to read real RT data you'll need to modify lpType from string to uint and this is RT API table:
private const uint RT_CURSOR = 0x00000001;
private const uint RT_BITMAP = 0x00000002;
private const uint RT_ICON = 0x00000003;
private const uint RT_MENU = 0x00000004;
private const uint RT_DIALOG = 0x00000005;
private const uint RT_STRING = 0x00000006;
private const uint RT_FONTDIR = 0x00000007;
private const uint RT_FONT = 0x00000008;
private const uint RT_ACCELERATOR = 0x00000009;
private const uint RT_RCDATA = 0x0000000a;
private const uint RT_MESSAGETABLE = 0x0000000b;