Internet explorer crash or freezes on BHO execution.

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi,

I have created a BHO using c# to print the label using the value from the web service.
The Internet Explorer crashes after 3 - 4 times of printing an order.
Please help me to overcome this. I want to stop IE crashing , without uninstalling the BHO.
Pasted the full code used.
using System;<br/>
using System.Collections.Generic;<br/>
using System.Text;<br/>
using SHDocVw;<br/>
using mshtml;<br/>
using System.Runtime.InteropServices;<br/>
using Microsoft.Win32;<br/>
using System.IO;<br/>
using System.Reflection;<br/>
using System.Diagnostics;<br/>
using System.Drawing;<br/>
using System.Drawing.Printing;<br/>
using System.Threading;<br/>
using Microsoft.Win32.SafeHandles;<br/>
using System.Management;<br/>
using System.Net.Sockets;<br/>
using ClientPrint_Test.LabelService;<br/>
<br/>
[ComVisible(true),<br/>
Guid("BA0C1A9A-78E7-11E1-AC1E-E8CE4724019B"),<br/>
ClassInterface(ClassInterfaceType.None)]<br/>
<br/>
<br/>
public class CPrinter : IObjectWithSite<br/>
{<br/>
[DllImport("Kernel32.dll")]<br/>
static extern IntPtr CreateFile(<br/>
string filename,<br/>
[MarshalAs(UnmanagedType.U4)]FileAccess fileaccess,<br/>
[MarshalAs(UnmanagedType.U4)]FileShare fileshare,<br/>
int securityattributes,<br/>
[MarshalAs(UnmanagedType.U4)]FileMode creationdisposition,<br/>
int flags,<br/>
IntPtr template);<br/>
<br/>
// HRESULT values used<br/>
const int E_FAIL = unchecked((int)0x80004005);<br/>
const int E_NOINTERFACE = unchecked((int)0x80004002);<br/>
<br/>
// threading and synchronization<br/>
private ManualResetEvent m_evCreateService = new ManualResetEvent(false);<br/>
<br/>
private IWebBrowser2 webBrowser;<br/>
protected DWebBrowserEvents2_Event m_pDWebBrowserEvents2;<br/>
private Thread PrintLabel;<br/>
<br/>
private string url;<br/>
private int shipmentID;<br/>
private int isMultiple; <br/>
private byte[] currentLabel; <br/>
<br/>
public void SetSite(object site)<br/>
{<br/>
if (m_pDWebBrowserEvents2 != null)<br/>
{<br/>
Release();<br/>
}<br/>
<br/>
webBrowser = site as WebBrowser;<br/>
if (!(webBrowser.FullName.ToUpper().EndsWith("IEXPLORE.EXE")))<br/>
{<br/>
Release();<br/>
return;<br/>
}<br/>
<br/>
m_pDWebBrowserEvents2 = webBrowser as DWebBrowserEvents2_Event;<br/>
<br/>
if (m_pDWebBrowserEvents2 != null)<br/>
{<br/>
m_pDWebBrowserEvents2.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(webBrowser_DownloadComplete);<br/>
}<br/>
else<br/>
{<br/>
Release();<br/>
return;<br/>
} <br/>
<br/>
}<br/>
<br/>
public void webBrowser_DownloadBegin()<br/>
{<br/>
<br/>
}<br/>
<br/>
public void webBrowser_DownloadComplete(object pDisp, ref object URL)<br/>
{<br/>
try<br/>
{<br/>
if (Marshal.Equals(webBrowser, pDisp))<br/>
{<br/>
<br/>
HTMLDocument doc = webBrowser.Document as HTMLDocument;<br/>
IHTMLElement el = null;<br/>
<br/>
// Collect the URL <br/>
string strDocumentURL = doc.url;<br/>
string strShipmentID = string.Empty;<br/>
<br/>
// IF URL is not blank then only go ahead<br/>
if (strDocumentURL != string.Empty)<br/>
{<br/>
// if the URL contains name of the page PrintingLabel.aspx, the take the Shipment ID from it<br/>
if (strDocumentURL.Contains("LabelPrinting/PrintingLabel.aspx"))<br/>
{<br/>
// split the string to Get the ID<br/>
string[] stringSeparators = new string[] { "?id=" };<br/>
string[] strArray = strDocumentURL.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);<br/>
if (strArray.Length == 2)<br/>
{<br/>
//strShipmentID = strArray[1];<br/>
string[] strSeparators = new string[] { "&isMultiple=" };<br/>
<br/>
string[] strSplittedArray = strArray[1].Split(strSeparators, StringSplitOptions.RemoveEmptyEntries);<br/>
if (strSplittedArray.Length == 2)<br/>
{<br/>
strShipmentID = strSplittedArray[0];<br/>
shipmentID = Convert.ToInt32(strSplittedArray[0]);<br/>
isMultiple = Convert.ToInt32(strSplittedArray[1]);<br/>
}<br/>
}<br/>
else<br/>
{<br/>
// set the 00 as Shipment ID<br/>
strShipmentID = "000000000";<br/>
shipmentID = 0;<br/>
isMultiple = 0;<br/>
}<br/>
<br/>
int length = doc.url.Substring(0, doc.url.LastIndexOf(/)).LastIndexOf(/) + 1;<br/>
this.url = doc.url.Substring(0, length) + "webservices/LabelWebService.asmx";<br/>
<br/>
PrintLabel = new Thread(this.PrintForCompleteShipment);<br/>
PrintLabel.SetApartmentState(ApartmentState.STA);<br/>
PrintLabel.Start();<br/>
}<br/>
}<br/>
}<br/>
<br/>
}<br/>
catch (Exception ex)<br/>
{<br/>
Release();<br/>
Marshal.ThrowExceptionForHR(E_FAIL);<br/>
}<br/>
}<br/>
<br/>
<br/>
public void GetSite(ref Guid guid, out IntPtr ppvSite)<br/>
{<br/>
<br/>
ppvSite = IntPtr.Zero;<br/>
if (webBrowser != null)<br/>
{<br/>
IntPtr pSite = IntPtr.Zero;<br/>
IntPtr punk = Marshal.GetIUnknownForObject(webBrowser);<br/>
Marshal.QueryInterface(punk, ref guid, out pSite);<br/>
Marshal.Release(punk);<br/>
Marshal.Release(punk); <br/>
<br/>
if (!punk.Equals(IntPtr.Zero))<br/>
{<br/>
ppvSite = pSite;<br/>
<br/>
}else<br/>
{<br/>
Release();<br/>
Marshal.ThrowExceptionForHR(E_NOINTERFACE);<br/>
}<br/>
<br/>
} else<br/>
{<br/>
Release();<br/>
Marshal.ThrowExceptionForHR(E_FAIL); <br/>
} <br/>
}<br/>
<br/>
public static string BHOKEYNAME = "Software\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects";<br/>
<br/>
[ComRegisterFunction]<br/>
public static void RegisterBHO(Type type)<br/>
{<br/>
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHOKEYNAME, true);<br/>
<br/>
if (registryKey == null)<br/>
registryKey = Registry.LocalMachine.CreateSubKey(BHOKEYNAME);<br/>
<br/>
string guid = type.GUID.ToString("B");<br/>
RegistryKey ourKey = registryKey.OpenSubKey(guid);<br/>
<br/>
if (ourKey == null)<br/>
ourKey = registryKey.CreateSubKey(guid);<br/>
<br/>
ourKey.SetValue("ClientPrint_Test", 1);<br/>
registryKey.Close();<br/>
ourKey.Close();<br/>
}<br/>
<br/>
[ComUnregisterFunction]<br/>
public static void UnregisterBHO(Type type)<br/>
{<br/>
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHOKEYNAME, true);<br/>
string guid = type.GUID.ToString("B");<br/>
<br/>
if (registryKey != null)<br/>
registryKey.DeleteSubKey(guid, false);<br/>
}<br/>
<br/>
protected void Release()<br/>
{<br/>
if (m_pDWebBrowserEvents2 != null)<br/>
{<br/>
Marshal.ReleaseComObject(m_pDWebBrowserEvents2);<br/>
m_pDWebBrowserEvents2 = null;<br/>
Array.Clear(currentLabel, 0, currentLabel.Length);<br/>
}<br/>
if (webBrowser != null)<br/>
{<br/>
Marshal.ReleaseComObject(webBrowser);<br/>
webBrowser = null;<br/>
Array.Clear(currentLabel, 0, currentLabel.Length);<br/>
}<br/>
}<br/>
<br/>
<br/>
public void PrintForCompleteShipment()<br/>
{<br/>
try<br/>
{ <br/>
byte[][] labels = null;<br/>
byte[][] returnLabels = null;<br/>
LabelWebService labelService = new LabelWebService();<br/>
if (isMultiple == 0) // Not Multiple but with return labels<br/>
{<br/>
returnLabels = labelService.GetLabelsByShipmentPackage(shipmentID);<br/>
foreach (byte[] inArray in returnLabels)<br/>
{<br/>
// byte[] inArray = imgData;<br/>
if (inArray != null && inArray.Length > 0)<br/>
{<br/>
string message = Convert.ToBase64String(inArray); <br/>
this.currentLabel = inArray;<br/>
PrintDocument printDocument = new PrintDocument();<br/>
printDocument.PrinterSettings = new PrinterSettings();<br/>
printDocument.PrinterSettings.PrinterName = this.DeterminePrinterName();<br/>
printDocument.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);<br/>
printDocument.Print();<br/>
<br/>
<br/>
}<br/>
}<br/>
<br/>
<br/>
}<br/>
else // for Multiple records<br/>
{<br/>
labels = labelService.GetLabels(shipmentID);<br/>
foreach (byte[] inArray in labels)<br/>
{<br/>
// byte[] inArray = imgData;<br/>
if (inArray != null && inArray.Length > 0)<br/>
{<br/>
string message = Convert.ToBase64String(inArray); <br/>
this.currentLabel = inArray;<br/>
PrintDocument printDocument = new PrintDocument();<br/>
printDocument.PrinterSettings = new PrinterSettings();<br/>
printDocument.PrinterSettings.PrinterName = this.DeterminePrinterName();<br/>
printDocument.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);<br/>
printDocument.Print(); <br/>
<br/>
}<br/>
}<br/>
<br/>
}<br/>
}<br/>
catch (Exception ex)<br/>
{<br/>
<br/>
} <br/>
<br/>
}<br/>
<br/>
private string DeterminePortName()<br/>
{<br/>
string returnValue = null;<br/>
<br/>
ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");<br/>
ManagementObjectCollection col = s.Get();<br/>
<br/>
foreach (ManagementObject printer in col)<br/>
{<br/>
if ((bool)printer["Default"])<br/>
{<br/>
returnValue = (string)printer["PortName"];<br/>
}<br/>
}<br/>
return returnValue; <br/>
}<br/>
<br/>
private string DeterminePrinterName()<br/>
{<br/>
string str = (string)null;<br/>
foreach (ManagementObject managementObject in new ManagementObjectSearcher("SELECT * FROM Win32_Printer").Get())<br/>
{<br/>
if ((bool)managementObject["Default"])<br/>
str = managementObject.Path.RelativePath.Replace("Win32_Printer.DeviceID=", string.Empty);<br/>
}<br/>
return str.Replace(""", string.Empty);<br/>
}<br/>
<br/>
private void pd_PrintPage(object sender, PrintPageEventArgs ev)<br/>
{<br/>
<br/>
int height = 600;<br/>
int width = 400;<br/>
int x = 3;<br/>
int y = 3;<br/>
<br/>
try<br/>
{<br/>
MemoryStream memoryStream = new MemoryStream(this.currentLabel, 0, this.currentLabel.Length);<br/>
memoryStream.Write(this.currentLabel, 0, this.currentLabel.Length);<br/>
Image image = Image.FromStream((Stream)memoryStream); <br/>
if (image.Height == 1200)<br/>
ev.Graphics.DrawImage(image, x, y, width, height);<br/>
else if (image.Height == 800)<br/>
ev.Graphics.DrawImage(image, 10, 10, 591, 392);<br/>
else<br/>
ev.Graphics.DrawImage(image, 3, 3, 400, 600);<br/>
ev.HasMorePages = false;<br/>
memoryStream.SetLength(0);<br/>
memoryStream.Close();<br/>
image.Dispose();<br/>
<br/>
}<br/>
catch(Exception ex)<br/>
{<br/>
<br/>
}<br/>
}<br/>
<br/>
}<br/>


View the full article
 

Similar threads

Back
Top