Printer properties Dialog Saved changes - c#

Hi i want to save the changes i made in printer preferences but they are ignored . I am doing this in c#
Please help me thanks
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
PrintDocument pd = new PrintDocument();
[DllImport("kernel32.dll")]
static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)] static extern bool GlobalUnlock(IntPtr hMem);
[DllImport("kernel32.dll")]
static extern IntPtr GlobalFree(IntPtr hMem);
[DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesW", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter,[MarshalAs(UnmanagedType.LPWStr)] string pDeviceName,IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);
private const int DM_IN_BUFFER = 8;
private const int DM_OUT_BUFFER = 2;
private const int DM_IN_PROMPT = 4;
private void ShowPrinterProperties(PrinterSettings settings)
{
IntPtr hDevMode = settings.GetHdevmode(settings.DefaultPageSettings);
IntPtr pDevMode = GlobalLock(hDevMode);
DocumentProperties(this.Handle, IntPtr.Zero, settings.PrinterName, pDevMode, pDevMode, DM_IN_PROMPT);
GlobalUnlock(hDevMode);
settings.SetHdevmode(hDevMode);
settings.DefaultPageSettings.SetHdevmode(hDevMode);
GlobalFree(hDevMode);
}
private void Form1_Load(object sender, EventArgs e)
{
// Add list of installed printers found to the combo box.
// The pkInstalledPrinters string will be used to provide the display string.
String pkInstalledPrinters;
for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
{
pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
comboBox1.Items.Add(pkInstalledPrinters);
//selectedPrinter = comboBox1.SelectedItem.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (pd.PrinterSettings.IsValid)
ShowPrinterProperties(pd.PrinterSettings);
else
MessageBox.Show("Invalid printer name");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
pd.PrinterSettings.PrinterName = comboBox1.Text;
// selectedPrinter = comboBox1.SelectedItem.ToString();
}
}

This should do the trick, tried and tested (make sure you have references to System.Drawing, System.Printing and ReachFramework assemblies):
public static bool GetPrinterProperties(PrinterDescription selectedPrinter, bool showPrintingPreferencesDialog)
{
int modeGetSizeOfBuffer = 0;
int modeCopy = 2;
int modeOutBuffer = 14;
IntPtr pointerHDevMode = new IntPtr();
IntPtr pointerDevModeData = new IntPtr();
try
{
PrintTicketConverter printTicketConverter = new PrintTicketConverter(selectedPrinter.FullName, selectedPrinter.ClientPrintSchemaVersion);
IntPtr mainWindowPtr = new WindowInteropHelper(Application.Current.MainWindow).Handle;
PrinterSettings printerSettings = new PrinterSettings();
pointerHDevMode = printerSettings.GetHdevmode(printerSettings.DefaultPageSettings);
IntPtr pointerDevMode = GlobalLock(pointerHDevMode);
int sizeNeeded = DocumentProperties(mainWindowPtr, IntPtr.Zero, selectedPrinter.FullName, IntPtr.Zero, pointerDevMode, modeGetSizeOfBuffer);
pointerDevModeData = Marshal.AllocHGlobal(sizeNeeded);
int result = -1;
if (!showPrintingPreferencesDialog)
{
result = DocumentProperties(mainWindowPtr, IntPtr.Zero, selectedPrinter.FullName, pointerDevModeData, pointerDevMode, modeCopy);
}
else
{
result = DocumentProperties(mainWindowPtr, IntPtr.Zero, selectedPrinter.FullName, pointerDevModeData, pointerDevMode, modeOutBuffer);
}
GlobalUnlock(pointerHDevMode);
if (result == 1)
{
byte[] devMode = new byte[sizeNeeded];
Marshal.Copy(pointerDevModeData, devMode, 0, sizeNeeded);
// set back new printing settings to selected printer.
selectedPrinter.DefaultPrintTicket = printTicketConverter.ConvertDevModeToPrintTicket(devMode);
return true;
}
}
finally
{
GlobalFree(pointerHDevMode);
Marshal.FreeHGlobal(pointerDevModeData);
}
return false;
}
The PrinterDescription class is as follows:
public class PrinterDescription
{
public string FullName { get; set; }
public int ClientPrintSchemaVersion { get; set; }
public PrintTicket DefaultPrintTicket { get; set; }
}
And the following imports are used:
[DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesW", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter, [MarshalAs(UnmanagedType.LPWStr)] string pDeviceName, IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);
[DllImport("kernel32.dll")]
private static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("kernel32.dll")]
private static extern bool GlobalUnlock(IntPtr hMem);
[DllImport("kernel32.dll")]
private static extern bool GlobalFree(IntPtr hMem);
After the dialog is ok'd, the print ticket will be updated. You may want to return the print ticket here, or use a copy of the default.

Related

I was trying to make a DLL Injector with C# Windows Form App and watched a tutorial on it but now I got one error [CS1503]

"Failed converting from System.IntPtr to byte[]"
I was trying to code an DLL injection but I didn´t workes as shown in the video...
Does anybody know how to fix this or if I need to add anything to the code???
I spent like 2 hours looking for a fix but I cant find it and I don´t know what I could do so I was thinking one of you could solve this problem?
This is my second Program I have programmed, show some specs of my Computer
using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
namespace Process_Hijacker
{
public partial class ProcessHijacker : Form
{
public ProcessHijacker()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Process[] processes = Process.GetProcesses();
foreach (Process p in processes)
{
processlist.Items.Add(p.ProcessName);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
DLLP = textBox1.Text;
}
private static string DLLP { get; set; }
private static string PN { get; set; }
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = this.openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
this.textBox1.Text = this.openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
}
//Injection Define
static readonly IntPtr INTPTR_ZERO = (IntPtr)0;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr OpenProcess(uint dwDesireAccess, int bintheritHandle, uint dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
static extern int CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpBAseAddress, byte[] Buffer, uint size, int lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
static extern int WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] buffer, uint size, int lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateRemoteThread(IntPtr hprocess, IntPtr lpThreadAttribute, IntPtr dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadID);
public static int Injection(string PN, string DLLP)
{
// 1 = Datei existiert nicht
// 2 = Prozess nicht aktiv
// 3 = Injektion Fehlgeschlagen
// 4 = Injektion Erfolgreich
if (!File.Exists(DLLP)) { return 1; }
uint _procid = 0;
Process[] _procs = Process.GetProcesses();
for (int i = 0; i < _procs.Length; i++)
{
if (_procs[i].ProcessName == PN)
{
_procid = (uint)_procs[i].Id;
}
}
if (_procid == 0) { return 2; }
if (!SI(_procid, DLLP))
{
return 3;
}
return 4;
}
public static bool SI(uint P, string DLLP)
{
IntPtr hndProc = OpenProcess((0x2 | 0x8 | 0x10 | 0x20 | 0x400), 1, P);
if (hndProc == INTPTR_ZERO) { return false; }
IntPtr lpAddress = VirtualAllocEx(hndProc, (IntPtr)null, (IntPtr)DLLP.Length, (0x1000 | 0x2000), 0x40);
if (lpAddress == INTPTR_ZERO)
{
return false;
}
byte[] bytes = Encoding.ASCII.GetBytes(DLLP);
if (WriteProcessMemory(hndProc, lpAddress, bytes, (uint)bytes.Length, 0) == 0)
{
return false;
}
CloseHandle(hndProc);
return true;
}
}
}

Show external process debug output

I'm working on an application that is a sound editor for a video game.
This application has an option to test the sounds in the game, to do this I use Process.Start with some special parameters to open the game .exe.
The game uses OutputDebugStringA() to print debug messages. The idea is to have a multiline textbox inside this form to show the debug messages only of the game process.
I've been doing some research and I know about the existence of DebugView from sysinternals, but is not useful for this case, I've also found DbMon.NET in code project, but for some reason causes the game to run very slow (with DebugView doesn't happen).
Any proposal?
Try this, you can specify the process ID inside the do while loop before printing it in the textbox.
public partial class Form1 : Form
{
private readonly IntPtr _bufferReadyEvent;
private readonly IntPtr _dataReadyEvent;
private readonly IntPtr _mapping;
private readonly IntPtr _file;
private const int WaitTimeout = 500;
private const uint WAIT_OBJECT_0 = 0;
private readonly Thread _reader;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetEvent(IntPtr hEvent);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr CreateFileMapping(IntPtr hFile, IntPtr lpFileMappingAttributes, FileMapProtection flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateEvent(IntPtr lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, FileMapAccess dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);
[Flags]
private enum FileMapAccess
{
FileMapRead = 0x0004,
}
[Flags]
private enum FileMapProtection
{
PageReadWrite = 0x04,
}
public Form1()
{
InitializeComponent();
_bufferReadyEvent = CreateEvent(IntPtr.Zero, false, false, "DBWIN_BUFFER_READY");
if (_bufferReadyEvent == IntPtr.Zero)
Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
_dataReadyEvent = CreateEvent(IntPtr.Zero, false, false, "DBWIN_DATA_READY");
if (_dataReadyEvent == IntPtr.Zero)
Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
_mapping = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, FileMapProtection.PageReadWrite, 0, 4096, "DBWIN_BUFFER");
if (_mapping == IntPtr.Zero)
Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
_file = MapViewOfFile(_mapping, FileMapAccess.FileMapRead, 0, 0, 1024);
if (_file == IntPtr.Zero)
Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
_reader = new Thread(Read)
{
IsBackground = true
};
_reader.Start();
}
private void Read()
{
try
{
do
{
SetEvent(_bufferReadyEvent);
uint wait = WaitForSingleObject(_dataReadyEvent, WaitTimeout);
if (wait == WAIT_OBJECT_0) // we don't care about other return values
{
int pid = Marshal.ReadInt32(_file);
string text = Marshal.PtrToStringAnsi(new IntPtr(_file.ToInt32() + Marshal.SizeOf(typeof(int)))).TrimEnd(null);
if (string.IsNullOrEmpty(text))
{
continue;
}
Textbox_DebugConsole.Invoke((MethodInvoker)delegate
{
Textbox_DebugConsole.AppendText(string.Format("{0} - {1}", pid, text + Environment.NewLine));
});
}
}
while (true);
}
catch (Exception e)
{
MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

c# Balloon Tip Text: Remove Project text from notification

I am using Balloon tip text in C# and everything is working as expected. However whenever my notifications appear, there will be subtext that correlates to the project name.
How do I remove this text?
Notification image:
notifyIcon1.Icon = new Icon(SystemIcons.Application, 40, 40);
notifyIcon1.Visible = true;
notifyIcon1.Text = "Application Installation";
notifyIcon1.BalloonTipText = "The App installaion has started.";
notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
notifyIcon1.BalloonTipTitle = "Test App Installation";
notifyIcon1.ShowBalloonTip(10000);
Okey so i think i have a start for you atleast. As you can see in the image below i managed to remove the name of the exectuable file that it was running from.
I found a example here how to show Balloon tip like Windows 10 Balloon tip without stretching icon and the example from cokeman19 where you can add your own custom icon. Although this does not seem to work when you dont want the exectuable name at the bottom.
If you want to do some changes i recommend you to look at https://msdn.microsoft.com/en-us/library/windows/desktop/bb773352(v=vs.85).aspx since it provied some nice hints on what to do.
Here is the code that i made a few changes too so we get what we want.
public class NotifyIconLarge : IDisposable
{
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int Shell_NotifyIcon(int message, NOTIFYICONDATA pnid);
[DllImport("Comctl32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr LoadIconWithScaleDown(IntPtr hinst, string pszName, int cx, int cy, out IntPtr phico);
[DllImport("user32.dll", SetLastError = true)]
static extern bool DestroyIcon(IntPtr hIcon);
private const int NIF_LARGE_ICON = 0x00000040;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class NOTIFYICONDATA
{
public int cbSize = Marshal.SizeOf(typeof(NOTIFYICONDATA));
public IntPtr hWnd;
public int uID;
public int uFlags;
public int uCallbackMessage;
public IntPtr hIcon;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szTip;
public int dwState;
public int dwStateMask;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string szInfo;
public int uTimeoutOrVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string szInfoTitle;
public int dwInfoFlags;
Guid guidItem;
public IntPtr hBalloonIcon;
}
private IntPtr _windowHandle;
private IntPtr _hIcon;
private bool _added;
private int _id = 1;
private string _tipText;
public NotifyIconLarge(IntPtr windowHandle, string tipText)
{
_windowHandle = windowHandle;
_tipText = tipText;
IntPtr result = LoadIconWithScaleDown(IntPtr.Zero, "", 0, 0, out _hIcon);
UpdateIcon(true);
}
private void UpdateIcon(bool showIconInTray)
{
NOTIFYICONDATA nOTIFYICONDATA = new NOTIFYICONDATA();
nOTIFYICONDATA.uCallbackMessage = 2048;
nOTIFYICONDATA.uFlags = 1;
nOTIFYICONDATA.hWnd = _windowHandle;
nOTIFYICONDATA.uID = _id;
nOTIFYICONDATA.hIcon = IntPtr.Zero;
nOTIFYICONDATA.szTip = null;
if (_hIcon != IntPtr.Zero)
{
nOTIFYICONDATA.uFlags |= 1;
nOTIFYICONDATA.hIcon = _hIcon;
}
nOTIFYICONDATA.uFlags |= 4;
nOTIFYICONDATA.szTip = _tipText;
nOTIFYICONDATA.hBalloonIcon = _hIcon;
if (showIconInTray)
{
if (!_added)
{
Shell_NotifyIcon(0, nOTIFYICONDATA);
_added = true;
}
else
{
Shell_NotifyIcon(1, nOTIFYICONDATA);
}
}
else
{
if (_added)
{
Shell_NotifyIcon(2, nOTIFYICONDATA);
_added = false;
}
}
}
public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTipIcon tipIcon)
{
NOTIFYICONDATA nOTIFYICONDATA = new NOTIFYICONDATA();
nOTIFYICONDATA.hWnd = _windowHandle;
nOTIFYICONDATA.uID = _id;
nOTIFYICONDATA.uFlags = 16;
nOTIFYICONDATA.uTimeoutOrVersion = timeout;
nOTIFYICONDATA.szInfoTitle = tipTitle;
nOTIFYICONDATA.szInfo = tipText;
switch (tipIcon)
{
case ToolTipIcon.None:
nOTIFYICONDATA.dwInfoFlags = NIF_LARGE_ICON;
break;
case ToolTipIcon.Info:
nOTIFYICONDATA.dwInfoFlags = 1;
break;
case ToolTipIcon.Warning:
nOTIFYICONDATA.dwInfoFlags = 2;
break;
case ToolTipIcon.Error:
nOTIFYICONDATA.dwInfoFlags = 3;
break;
}
int ret = Shell_NotifyIcon(1, nOTIFYICONDATA);
}
public void RemoveFromTray()
{
UpdateIcon(false);
if (_hIcon != IntPtr.Zero)
DestroyIcon(_hIcon);
}
~NotifyIconLarge()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
RemoveFromTray();
}
}
So first you declare the NotifyIconLarge class somewhere.
private NotifyIconLarge _nil;
Then to create a notify popup you use the following code:
_nil = new NotifyIconLarge(Handle, "Icon Tip");
_nil.ShowBalloonTip(10000, "Balloon Title", "Balloon Text", ToolTipIcon.None);
When you are finished with the tray remove it:
_nil.RemoveFromTray();
Credits to cokeman19 for most of the code

How to set advanced printer settings [duplicate]

We have a project of managing printing documents. At first I wonder why printing options couldn't be set up in single place. For example printer tray selection for first page and for other pages can be done using MS Word automation:
var doc = _applicationObject.Documents.OpenNoRepairDialog(FileName: ref sourceFile, ReadOnly: ref readOnly,
AddToRecentFiles: ref addToRecentFiles,
Visible: ref visible);
doc.PageSetup.FirstPageTray = (WdPaperTray) firstPageTrayCode;
doc.PageSetup.OtherPagesTray = (WdPaperTray) otherPagesTrayCode;
_applicationObject.ActivePrinter = printerPath;
doc.Activate();
_applicationObject.PrintOut(Background: ref backgroundPrint, FileName: sourceFile);
doc.Close(ref saveChanges, ref _missing, ref _missing);
In the code above printer tray is specified as integer because some printers have not standart values for trays (we had this issue with HP - it's tray codes described here). So we first retrieve what trays printer have, using code:
var setting = new PrinterSettings();
setting.PrinterName = myPrinterName;
foreach (PaperSource tray in setting.PaperSources)
{
Console.WriteLine("\t{0}: #{1}", tray.SourceName, tray.RawKind);
}
And this code works with no problems.
But there is no way to specify duplex and staple options here. Duplex can be done, using driver functions OpenPrinter and SetPrinter, like described here and recommended by Microsoft as well in this forum thread.
Staple is completely unclear and if somebody knows by the way how to implement this, please let me know. Using Stapling enum, like in this MSDN article is useless as it requires custom rendering of the document to print.
I described the situation and how parts were implemented. That works fine on our environment: Windows Server 2008 R2, MS Office 2010 x32, Printers HP LaserJet P2055 and Ricoh Nashuatec DSm635. Tested with native and universal PCL6/PCL5e drivers: duplex and tray selection works as expected.
But after deployment the application to client, printers (HP LaserJet 4250 and Ricoh Aficio MP C7501) do printing always from default tray and without duplex. Tried few different drivers with exactly the same result.
In both environments printers are network printers. So to make them apply duplex setting, using printer driver, we needed to install local driver on server and make a local printer, as recommended my Microsoft on this support forum thread.
Though environments and printers used looks very similar, one works while other do not. Any help will be highly appreciated.
In case someone else needs it, I came up with a workaround, based on storing printer settings memory block in a binary file and then restoring it. The idea was described in this blog post, but it didn't work for me when simply copy-pasted (it worked only for some drivers and for some settings while other printing options were ignored).
So I remade it a bit so that now it can support all settings I've tried on any printer (with compatible driver) I've tested. Of course if you use driver of another printer for example it won't work.
The disadvantage of thi approach is of course that you should first set default printer preferences (in Control Panel) to what you need. That isn't always possible of course, but at least in some cases it can help.
So the full source code of a test util which is capable to store printer settings into a file, load this file again into printer and print a document using the specified settings file:
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Office.Interop.Word;
namespace PrintAdvancedTest
{
[StructLayout(LayoutKind.Sequential)]
public struct PRINTER_DEFAULTS
{
public int pDatatype;
public int pDevMode;
public int DesiredAccess;
}
[StructLayout(LayoutKind.Sequential)]
public struct PRINTER_INFO_2
{
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pServerName;
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pPrinterName;
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pShareName;
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pPortName;
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pDriverName;
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pComment;
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pLocation;
public IntPtr pDevMode;
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pSepFile;
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pPrintProcessor;
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pDatatype;
[MarshalAs(UnmanagedType.LPStr)]
public readonly string pParameters;
public IntPtr pSecurityDescriptor;
public readonly Int32 Attributes;
public readonly Int32 Priority;
public readonly Int32 DefaultPriority;
public readonly Int32 StartTime;
public readonly Int32 UntilTime;
public readonly Int32 Status;
public readonly Int32 cJobs;
public readonly Int32 AveragePPM;
}
public class PrintSettings
{
private const short CCDEVICENAME = 32;
private const short CCFORMNAME = 32;
//Constants for DEVMODE
// Constants for DocumentProperties
private const int DM_MODIFY = 8;
private const int DM_COPY = 2;
private const int DM_IN_BUFFER = DM_MODIFY;
private const int DM_OUT_BUFFER = DM_COPY;
// const intants for dmOrientation
private const int DMORIENT_PORTRAIT = 1;
private const int DMORIENT_LANDSCAPE = 2;
// const intants for dmPrintQuality
private const int DMRES_DRAFT = (-1);
private const int DMRES_HIGH = (-4);
private const int DMRES_LOW = (-2);
private const int DMRES_MEDIUM = (-3);
// const intants for dmTTOption
private const int DMTT_BITMAP = 1;
private const int DMTT_DOWNLOAD = 2;
private const int DMTT_DOWNLOAD_OUTLINE = 4;
private const int DMTT_SUBDEV = 3;
// const intants for dmColor
private const int DMCOLOR_COLOR = 2;
private const int DMCOLOR_MONOCHROME = 1;
// const intants for dmCollate
private const int DMCOLLATE_FALSE = 0;
private const int DMCOLLATE_TRUE = 1;
// const intants for dmDuplex
private const int DMDUP_HORIZONTAL = 3;
private const int DMDUP_SIMPLEX = 1;
private const int DMDUP_VERTICAL = 2;
//const for security access
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);
/* field selection bits */
private const int DM_ORIENTATION = 0x00000001;
private const int DM_PAPERSIZE = 0x00000002;
private const int DM_PAPERLENGTH = 0x00000004;
private const int DM_PAPERWIDTH = 0x00000008;
private const int DM_SCALE = 0x00000010;
private const int DM_POSITION = 0x00000020;
private const int DM_NUP = 0x00000040;
private const int DM_DISPLAYORIENTATION = 0x00000080;
private const int DM_COPIES = 0x00000100;
private const int DM_DEFAULTSOURCE = 0x00000200;
private const int DM_PRINTQUALITY = 0x00000400;
private const int DM_COLOR = 0x00000800;
private const int DM_DUPLEX = 0x00001000;
private const int DM_YRESOLUTION = 0x00002000;
private const int DM_TTOPTION = 0x00004000;
private const int DM_COLLATE = 0x00008000;
private const int DM_FORMNAME = 0x00010000;
private const int DM_LOGPIXELS = 0x00020000;
private const int DM_BITSPERPEL = 0x00040000;
private const int DM_PELSWIDTH = 0x00080000;
private const int DM_PELSHEIGHT = 0x00100000;
private const int DM_DISPLAYFLAGS = 0x00200000;
private const int DM_DISPLAYFREQUENCY = 0x00400000;
private const int DM_ICMMETHOD = 0x00800000;
private const int DM_ICMINTENT = 0x01000000;
private const int DM_MEDIATYPE = 0x02000000;
private const int DM_DITHERTYPE = 0x04000000;
private const int DM_PANNINGWIDTH = 0x08000000;
private const int DM_PANNINGHEIGHT = 0x10000000;
private const int DM_DISPLAYFIXEDOUTPUT = 0x20000000;
[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;
}
static void Main(string[] args)
{
Dictionary<string, Action> commands = new Dictionary<string, Action>
{
{"save", PrinterPreferencesSave},
{"print", PrinterPreferencesPrint},
{"set", PrinterPreferencesSet},
{"info", PrinterInfo}
};
while (true)
{
Console.Write("Command ({0}): ", string.Join(", ", commands.Keys));
string command = Console.ReadLine();
Action action;
if (!commands.TryGetValue(command, out action))
{
Console.WriteLine("Invalid command");
}
else
{
action();
}
}
}
static void PrinterPreferencesSave()
{
Console.Write("Printer name: ");
string printerName = Console.ReadLine();
Console.Write("Settings file path format: ");
string SettingsFileNameFormat = Console.ReadLine();
string testName;
while (true)
{
Console.Write("SAVE: Settings set name: ");
testName = Console.ReadLine();
if (testName == "end")
{
break;
}
getDevMode(printerName, string.Format(SettingsFileNameFormat, testName));
}
}
static void PrinterPreferencesPrint()
{
Console.Write("Printer name: ");
string printerName = Console.ReadLine();
Console.Write("Settings file path format: ");
string SettingsFileNameFormat = Console.ReadLine();
Console.Write("Document to print: ");
string docToPrintPath = Console.ReadLine();
string testName;
while (true)
{
Console.Write("PRINT: Settings set name: ");
testName = Console.ReadLine();
if (testName == "end")
{
break;
}
string filePath = string.Format(SettingsFileNameFormat, testName);
if (!File.Exists(filePath))
{
Console.WriteLine("File {0} not exists", filePath);
return;
}
var success = setDevMode(printerName, filePath);
if (success)
{
PrintWordDocument(docToPrintPath, printerName);
}
}
}
static void PrinterPreferencesSet()
{
Console.Write("Printer name: ");
string printerName = Console.ReadLine();
Console.Write("Settings file path format: ");
string SettingsFileNameFormat = Console.ReadLine();
string testName;
while (true)
{
Console.Write("SET: Settings set name: ");
testName = Console.ReadLine();
if (testName == "end")
{
break;
}
string filePath = string.Format(SettingsFileNameFormat, testName);
if (!File.Exists(filePath))
{
Console.WriteLine("File {0} not exists", filePath);
return;
}
var success = setDevMode(printerName, filePath);
if(!success)
{
Console.WriteLine("Failed");
}
}
}
private static void PrinterInfo()
{
Console.Write("Printer name: ");
string printerName = Console.ReadLine();
IntPtr hDevMode; // handle to the DEVMODE
IntPtr pDevMode; // pointer to the DEVMODE
DEVMODE devMode; // the actual DEVMODE structure
//var printController = new StandardPrintController();
PrinterSettings printerSettings = new PrinterSettings();
printerSettings.PrinterName = printerName;
// Get a handle to a DEVMODE for the default printer settings
hDevMode = printerSettings.GetHdevmode(printerSettings.DefaultPageSettings);
// Obtain a lock on the handle and get an actual pointer so Windows won't
// move it around while we're futzing with it
pDevMode = GlobalLock(hDevMode);
// Marshal the memory at that pointer into our P/Invoke version of DEVMODE
devMode = (DEVMODE)Marshal.PtrToStructure(pDevMode, typeof(DEVMODE));
Dictionary<string, int> dmConstants = new Dictionary<string, int>
{
{"DM_ORIENTATION", 0x00000001},
{"DM_PAPERSIZE", 0x00000002},
{"DM_PAPERLENGTH", 0x00000004},
{"DM_PAPERWIDTH", 0x00000008},
{"DM_SCALE", 0x00000010},
{"DM_POSITION", 0x00000020},
{"DM_NUP", 0x00000040},
{"DM_DISPLAYORIENTATION", 0x00000080},
{"DM_COPIES", 0x00000100},
{"DM_DEFAULTSOURCE", 0x00000200},
{"DM_PRINTQUALITY", 0x00000400},
{"DM_COLOR", 0x00000800},
{"DM_DUPLEX", 0x00001000},
{"DM_YRESOLUTION", 0x00002000},
{"DM_TTOPTION", 0x00004000},
{"DM_COLLATE", 0x00008000},
{"DM_FORMNAME", 0x00010000},
{"DM_LOGPIXELS", 0x00020000},
{"DM_BITSPERPEL", 0x00040000},
{"DM_PELSWIDTH", 0x00080000},
{"DM_PELSHEIGHT", 0x00100000},
{"DM_DISPLAYFLAGS", 0x00200000},
{"DM_DISPLAYFREQUENCY", 0x00400000},
{"DM_ICMMETHOD", 0x00800000},
{"DM_ICMINTENT", 0x01000000},
{"DM_MEDIATYPE", 0x02000000},
{"DM_DITHERTYPE", 0x04000000},
{"DM_PANNINGWIDTH", 0x08000000},
{"DM_PANNINGHEIGHT", 0x10000000},
{"DM_DISPLAYFIXEDOUTPUT", 0x20000000},
};
Console.WriteLine("Allow set: {0}. Details: {1}", Convert.ToString(devMode.dmFields, 16), string.Join(",", dmConstants.Where(c=>(devMode.dmFields & c.Value)==c.Value).Select(c=>c.Key)));
//private const int DM_POSITION = 0x00000020;
//private const int DM_NUP = 0x00000040;
//private const int DM_DISPLAYORIENTATION = 0x00000080;
//private const int DM_DEFAULTSOURCE = 0x00000200;
//private const int DM_PRINTQUALITY = 0x00000400;
//private const int DM_COLOR = 0x00000800;
//private const int DM_YRESOLUTION = 0x00002000;
//private const int DM_TTOPTION = 0x00004000;
//private const int DM_FORMNAME = 0x00010000;
//private const int DM_LOGPIXELS = 0x00020000;
//private const int DM_BITSPERPEL = 0x00040000;
//private const int DM_PELSWIDTH = 0x00080000;
//private const int DM_PELSHEIGHT = 0x00100000;
//private const int DM_DISPLAYFLAGS = 0x00200000;
//private const int DM_DISPLAYFREQUENCY = 0x00400000;
//private const int DM_ICMMETHOD = 0x00800000;
//private const int DM_ICMINTENT = 0x01000000;
//private const int DM_MEDIATYPE = 0x02000000;
//private const int DM_DITHERTYPE = 0x04000000;
//private const int DM_PANNINGWIDTH = 0x08000000;
//private const int DM_PANNINGHEIGHT = 0x10000000;
//private const int DM_DISPLAYFIXEDOUTPUT = 0x20000000;
WriteDevModePropertyInfo("DeviceName", devMode.dmDeviceName, null);
WriteDevModePropertyInfo("SpecVersion", devMode.dmSpecVersion.ToString(), null);
WriteDevModePropertyInfo("DriverVersion", devMode.dmDriverVersion.ToString(), null);
WriteDevModePropertyInfo("Size", devMode.dmSize.ToString(), null);
WriteDevModePropertyInfo("DriverExtra", devMode.dmDriverExtra.ToString(), null);
WriteDevModePropertyInfo("Orientation", devMode.dmOrientation.ToString(), (devMode.dmFields & DM_ORIENTATION) == DM_ORIENTATION);
WriteDevModePropertyInfo("PaperSize", devMode.dmPaperSize.ToString(), (devMode.dmFields & DM_PAPERSIZE) == DM_PAPERSIZE);
WriteDevModePropertyInfo("PaperLength", devMode.dmPaperLength.ToString(), (devMode.dmFields & DM_PAPERLENGTH) == DM_PAPERLENGTH);
WriteDevModePropertyInfo("PaperWidth", devMode.dmPaperWidth.ToString(), (devMode.dmFields & DM_PAPERWIDTH) == DM_PAPERWIDTH);
WriteDevModePropertyInfo("Scale", devMode.dmScale.ToString(), (devMode.dmFields & DM_SCALE) == DM_SCALE);
WriteDevModePropertyInfo("Copies", devMode.dmCopies.ToString(), (devMode.dmFields & DM_COPIES) == DM_COPIES);
WriteDevModePropertyInfo("Duplex", devMode.dmDuplex.ToString(), (devMode.dmFields & DM_DUPLEX) == DM_DUPLEX);
WriteDevModePropertyInfo("YResolution", devMode.dmYResolution.ToString(), null);
WriteDevModePropertyInfo("TTOption", devMode.dmTTOption.ToString(), null);
WriteDevModePropertyInfo("Collate", devMode.dmCollate.ToString(), (devMode.dmFields & DM_COLLATE) == DM_COLLATE);
WriteDevModePropertyInfo("FormName", devMode.dmFormName.ToString(), null);
WriteDevModePropertyInfo("UnusedPadding", devMode.dmUnusedPadding.ToString(), null);
WriteDevModePropertyInfo("BitsPerPel", devMode.dmBitsPerPel.ToString(), null);
WriteDevModePropertyInfo("PelsWidth", devMode.dmPelsWidth.ToString(), null);
WriteDevModePropertyInfo("PelsHeight", devMode.dmPelsHeight.ToString(), null);
WriteDevModePropertyInfo("DisplayFlags", devMode.dmDisplayFlags.ToString(), null);
WriteDevModePropertyInfo("DisplayFrequency", devMode.dmDisplayFlags.ToString(), null);
}
private static void WriteDevModePropertyInfo(string settingName, string value, bool? allowSet)
{
Console.WriteLine("{0} {1} {2}", allowSet.HasValue ? (allowSet.Value ? "+" : "-") : " ", settingName.PadRight(20, '.'), value);
}
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GlobalFree(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GlobalLock(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GlobalUnlock(IntPtr handle);
[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);
[DllImport("kernel32.dll")]
static extern IntPtr GlobalAlloc(uint uFlags, int dwBytes);
public static void getDevMode(string printerName, string filepath)
{
PRINTER_DEFAULTS PrinterValues = new PRINTER_DEFAULTS();
PrinterValues.pDatatype = 0;
PrinterValues.pDevMode = 0;
PrinterValues.DesiredAccess = PRINTER_ALL_ACCESS;
IntPtr ptrZero = IntPtr.Zero;
IntPtr hPrinter;
IntPtr pDevMode = new IntPtr();
//get printer handle
OpenPrinter(printerName, out hPrinter, ref PrinterValues);
//allocate memory for ptr to devmode, 0 argument retrieves bytes required
int bytes = DocumentProperties(new IntPtr(0), hPrinter, printerName, ptrZero, ref pDevMode, 0);
pDevMode = GlobalAlloc(0, bytes);
//set the pointer
DocumentProperties(new IntPtr(0), hPrinter, printerName, pDevMode, ref ptrZero, DM_OUT_BUFFER);
//write the devMode to a file
using (FileStream fs = new FileStream(filepath, FileMode.Create))
{
for (int i = 0; i < bytes; i++)
{
fs.WriteByte(Marshal.ReadByte(pDevMode, i));
}
}
//free resources
GlobalFree(pDevMode);
ClosePrinter(hPrinter);
}
public static bool setDevMode(string printerName, string filepath)
{
if(!File.Exists(filepath))
{
return false;
}
IntPtr hPrinter;
int bytes = 0;
IntPtr pPInfo;
IntPtr pDevMode;
PRINTER_INFO_2 pInfo = new PRINTER_INFO_2();
PRINTER_DEFAULTS PrinterValues = new PRINTER_DEFAULTS();
PrinterValues.pDatatype = 0;
PrinterValues.pDevMode = 0;
PrinterValues.DesiredAccess = PRINTER_ALL_ACCESS;
//retrieve the devmode from file
using (FileStream fs = new FileStream(filepath, FileMode.Open))
{
int length = Convert.ToInt32(fs.Length);
pDevMode = GlobalAlloc(0, length);
for (int i = 0; i < length; i++)
{
Marshal.WriteByte(pDevMode, i, (byte)fs.ReadByte());
}
}
//get printer handle
OpenPrinter(printerName, out hPrinter, ref PrinterValues);
//get bytes for printer info structure and allocate memory
GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out bytes);
if (bytes == 0)
{
throw new Exception("Get Printer Failed");
}
pPInfo = GlobalAlloc(0, bytes);
//set pointer to printer info
GetPrinter(hPrinter, 2, pPInfo, bytes, out bytes);
//place the printer info structure
pInfo = (PRINTER_INFO_2)Marshal.PtrToStructure(pPInfo, typeof(PRINTER_INFO_2));
//insert the new devmode
pInfo.pDevMode = pDevMode;
pInfo.pSecurityDescriptor = IntPtr.Zero;
//set pointer to new printer info
Marshal.StructureToPtr(pInfo, pPInfo, true);
//update
SetPrinter(hPrinter, 2, pPInfo, 0);
//free resources
GlobalFree(pPInfo);
GlobalFree(pDevMode);
ClosePrinter(hPrinter);
return true;
}
private static void PrintWordDocument(string path, string printerName)
{
object readOnly = true;
object addToRecentFiles = false;
object visible = false;
object backgroundPrint = false;
object saveChanges = false;
object sourceFile = path;
var wordApplication = new Application();
var doc = wordApplication.Documents.OpenNoRepairDialog(FileName: ref sourceFile, ReadOnly: ref readOnly,
AddToRecentFiles: ref addToRecentFiles,
Visible: ref visible);
wordApplication.ActivePrinter = printerName;
doc.Activate();
wordApplication.PrintOut(Background: ref backgroundPrint, FileName: sourceFile);
object _missing = Type.Missing;
doc.Close(ref saveChanges, ref _missing, ref _missing);
}
}
}
UPDATE 2018-12-04 (in 5,5 years): There was a nasty rare problem with Marshal.StructureToPtr call in this code and today I finally got an answer to that question (see comment from Hans Passant). I'm not able to verify if that actually works since I no longer work on that project, but it seems you may need to apply that fix if you try using this code.

Cant create HTML document from Hwnd using C#

We have an existing piece of software that uses shellwidnows to access an internet explorer page and modify data on a form. However, we are porting it to Citrix seamless application and shell windows does not work there.
I have looked around on the internet and found a way to create a HtmlDocument from an existing IE window.
However, I am having a problem when trying to run "SendMessageTimeout". It runs without error but the result returned is 0 when it should be a non-zero amount. And thus, I can not go to the next phase of creating the HTML Document.
The line causing the problem is:
IntPtr result = SendMessageTimeout(htmlWindow, lMsg, IntPtr.Zero, IntPtr.Zero, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 1000, out lRes);
Here is the full code. Iam using VS 2008 due to corporate conventions. I am new to C# so some conventions and styling may be incorrect. Thanks for any help.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using mshtml;
using System.Diagnostics;
public delegate bool IECallBack(int hwnd, int lParam);
public delegate bool IEChildCallBack(int hWndParent, int lpEnumFunc, int lParam);
namespace GetIEWindows
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("Oleacc.Dll")]
public static extern int ObjectFromLresult(UIntPtr lResult, UUID _riid, int wParam, mshtml.HTMLDocument _ppvObject);
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
private static extern int FindWindowEx(int parentWindow, int childWindow, string _ClassName, string _WindowName);
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.Dll")]
public static extern int EnumWindows(IECallBack x, long y);
[DllImport("user32.Dll")]
public static extern int EnumChildWindows(int parent, IECallBack x, long y);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, GetWindow_Cmd uCmd);
[DllImport("User32.Dll")]
public static extern void GetWindowText(IntPtr h, StringBuilder s, long nMaxCount);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("User32.Dll")]
public static extern void GetClassName(int h, StringBuilder s, int
nMaxCount);
[DllImport("User32.Dll")]
public static extern uint RegisterWindowMessage(string lpString);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(IntPtr windowHandle, uint Msg, IntPtr wParam, IntPtr lParam, SendMessageTimeoutFlags flags, uint timeout, out UIntPtr result);
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
}
[Flags]
public enum SendMessageTimeoutFlags : uint
{
SMTO_NORMAL = 0x0,
SMTO_BLOCK = 0x1,
SMTO_ABORTIFHUNG = 0x2,
SMTO_NOTIMEOUTIFNOTHUNG = 0x8
}
public const int SMTO_ABORTIFHUNG = 0x2;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct UUID
{
public long Data1;
public int Data2;
public int Data3;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] Data4;
}
public static mshtml.HTMLDocument GetHTMLContent(IntPtr htmlWindow)
{
HTMLDocument htmlDocument = new mshtml.HTMLDocument();
HTMLDocument thedoc = new mshtml.HTMLDocument();
IHTMLDocument htmlDoc = null;
Guid guid = new Guid("626FC520-A41E-11cf-A731-00A0C9082637");
int foundWindow = htmlWindow.ToInt32();
string htmlContent = "";
UUID IID_IHTMLDocument = new UUID();
UIntPtr lRes;
uint lMsg = 0;
int hr = 0;
if (foundWindow != 0)
{
// Register the message
lMsg = RegisterWindowMessage("WM_HTML_GETOBJECT");
//lMsg = RegisterWindowMessage("WM_GETTEXT");
// Get the object
IntPtr result = SendMessageTimeout(htmlWindow, lMsg, IntPtr.Zero, IntPtr.Zero, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 1000, out lRes);
if (result.ToInt32() != 0)
{
if (lRes != UIntPtr.Zero)
{
// Initialize the interface ID
IID_IHTMLDocument.Data1 = 0x626FC520;
IID_IHTMLDocument.Data2 = 0xA41E;
IID_IHTMLDocument.Data3 = 0x11CF;
IID_IHTMLDocument.Data4 = new byte[8];
IID_IHTMLDocument.Data4[0] = 0xA7;
IID_IHTMLDocument.Data4[1] = 0x31;
IID_IHTMLDocument.Data4[2] = 0x0;
IID_IHTMLDocument.Data4[3] = 0xA0;
IID_IHTMLDocument.Data4[4] = 0xC9;
IID_IHTMLDocument.Data4[5] = 0x8;
IID_IHTMLDocument.Data4[6] = 0x26;
IID_IHTMLDocument.Data4[7] = 0x37;
// Get the object from lRes
try
{
hr = ObjectFromLresult(lRes, IID_IHTMLDocument, 0, thedoc);
//htmlDoc = (mshtml.IHTMLDocument)ObjectFromLresult(, IID_IHTMLDocument, 0, htmlDoc);
}
catch (Exception e)
{
MessageBox.Show("Did not get IHTMLDocument: " + e.Message);
}
}
}
}
return thedoc;
}
public static void getHWnd()
{
string currentTitle;
string windowName = null;
string windowClass = "#32770";
HTMLDocument pageToBeEdited;
IntPtr hWnd = FindWindow(windowClass, windowName);
while (hWnd.ToInt32() != 0) {
int length = GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(length + 1);
GetWindowText(hWnd, sb, sb.Capacity);
currentTitle = sb.ToString();
if (currentTitle.Contains("Internet Explorer")) {
pageToBeEdited = GetHTMLContent(hWnd);
return;
}
hWnd = GetWindow(hWnd, GetWindow_Cmd.GW_HWNDNEXT);
}
return;
}
private void btnRun_Click(object sender, EventArgs e)
{
getHWnd();
}
}
}
For anybody who is interested, the problem was resolved by using a different way of getHWnd:
public static IntPtr getHWnd(string title)
{
IntPtr hWnd = FindWindow(null, title);
BringWindowToTop(hWnd);
SetActiveWindow(hWnd);
SetForegroundWindow(hWnd);
Thread.Sleep(500);
foreach (Process process in Process.GetProcessesByName("IExplore"))
{
if (process.MainWindowTitle.ToLower().Contains(title.ToLower()))
{
hWnd = process.MainWindowHandle;
break;
}
}
EnumProc proc = new EnumProc(EnumWindows);
EnumChildWindows(hWnd, proc, ref hWnd);
return hWnd;
}
public HTMLDocument GetHTMLDocument(IntPtr hWnd)
{
HTMLDocument document = null;
int iMsg = 0;
int iRes = 0;
iMsg = RegisterWindowMessage("WM_HTML_GETOBJECT");
if (iMsg != 0)
{
SendMessageTimeout(hWnd, iMsg, 0, 0, SMTO_ABORTIFHUNG, 1000, out iRes);
if (iRes != 0)
{
int hr = ObjectFromLresult(iRes, ref IID_IHTMLDocument, 0, ref document);
}
}
return document;
}
private static int EnumWindows(IntPtr hWnd, ref IntPtr lParam)
{
int iRet = 1;
StringBuilder classname = new StringBuilder(128);
GetClassName(hWnd, classname, classname.Capacity);
if ((bool)(string.Compare(classname.ToString(), "Internet Explorer_Server") == 0))
{
lParam = hWnd;
iRet = 0;
}
return iRet;
}
Here is how you can get HTMLDocument using Hwnd :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using mshtml;
namespace HookBrowser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
#region API CALLS
[DllImport("user32.dll", EntryPoint = "GetClassNameA")]
public static extern int GetClassName(IntPtr hwnd, StringBuilder lpClassName, int nMaxCount);
/*delegate to handle EnumChildWindows*/
public delegate int EnumProc(IntPtr hWnd, ref IntPtr lParam);
[DllImport("user32.dll")]
public static extern int EnumChildWindows(IntPtr hWndParent, EnumProc lpEnumFunc, ref IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "RegisterWindowMessageA")]
public static extern int RegisterWindowMessage(string lpString);
[DllImport("user32.dll", EntryPoint = "SendMessageTimeoutA")]
public static extern int SendMessageTimeout(IntPtr hwnd, int msg, int wParam, int lParam, int fuFlags, int uTimeout, out int lpdwResult);
[DllImport("OLEACC.dll")]
public static extern int ObjectFromLresult(int lResult, ref Guid riid, int wParam, ref IHTMLDocument2 ppvObject);
public const int SMTO_ABORTIFHUNG = 0x2;
public Guid IID_IHTMLDocument = new Guid("626FC520-A41E-11CF-A731-00A0C9082637");
#endregion
public IHTMLDocument2 document;
private void button1_Click(object sender, EventArgs e)
{
document = documentFromDOM();
/// check that we have hold of the IHTMLDocument2...
if (!(bool)(document == null))
{
this.Text = document.url;
}
}
private IHTMLDocument2 documentFromDOM()
{
Process[] processes = Process.GetProcessesByName("iexplore");
if (processes.Length > 0)
{
IntPtr hWnd = processes[0].MainWindowHandle;
int lngMsg = 0;
int lRes;
EnumProc proc = new EnumProc(EnumWindows);
EnumChildWindows(hWnd, proc, ref hWnd);
if (!hWnd.Equals(IntPtr.Zero))
{
lngMsg = RegisterWindowMessage("WM_HTML_GETOBJECT");
if (lngMsg != 0)
{
SendMessageTimeout(hWnd, lngMsg, 0, 0, SMTO_ABORTIFHUNG, 1000, out lRes);
if (!(bool)(lRes == 0))
{
int hr = ObjectFromLresult(lRes, ref IID_IHTMLDocument, 0, ref document);
if ((bool)(document == null))
{
MessageBox.Show("NoLDocument Found!", "Warning");
}
}
}
}
}
return document;
}
private int EnumWindows(IntPtr hWnd, ref IntPtr lParam)
{
int retVal = 1;
StringBuilder classname = new StringBuilder(128);
GetClassName(hWnd, classname, classname.Capacity);
/// check if the instance we have found is Internet Explorer_Server
if ((bool)(string.Compare(classname.ToString(), "Internet Explorer_Server") == 0))
{
lParam = hWnd;
retVal = 0;
}
return retVal;
}
}
}
Please refer to this link for more info :
http://www.xtremevbtalk.com/code-library/295336-internet-explorer-dom-using-objectfromlresult.html

Categories

Resources