50% OFF!!!

Showing posts with label winforms. Show all posts
Showing posts with label winforms. Show all posts

Thursday, December 22, 2016

c# | WebBrowser control - programmatically select item on html `select`

Hi There,

As many times, we need to interact with the C# (.Net) Webbrowser Control, 
it is useful to be able to interact and programmatically change the selected item 
on an HTML select control.

I don't know, why it is hard to find this easy solution, but the code is as follow:


HtmlElementCollection col = webBrowser1.Document.GetElementsByTagName("select") 
foreach (HtmlElement heItem in col) 
{ 
  if (heItem.GetAttribute("className").Contains("exampleClassName") == true) 
  { 
    heItem.SetAttribute("selectedIndex", "3"); // select value at #3
    break; // incase of needed... 
  } 
}  


And finally, just easy as u code...


If you need change by value and not by index,
I assume you can check the values of the select control (sometimes called: dropdown),
and once you find the correct index of the desired value,
use the code above.



MDB-BLOG :)

Wednesday, February 13, 2013

c# Winforms WebBrowser - Clear all cookies

Hello,
I recently search for a method to delete all cookies from the build in .NET WinForms WebBrowser control.
I didn't found any working solution for it, nor working example.
It being told to use InternetSetOption, but nothing found about it.
So, i will write here my solution for clearing and deleting all cookies.
My solution using InternetSetOption with the option flag: INTERNET_OPTION_SUPPRESS_BEHAVIOR, which described as:

A general purpose option that is used to suppress behaviors on a process-wide basis. The lpBuffer parameter of the function must be a pointer to a DWORD containing the specific behavior to suppress. This option cannot be queried with InternetQueryOption.

This option flag should be used together with INTERNET_SUPPRESS_COOKIE_PERSIST options, which means:

Suppresses the persistence of cookies, even if the server has specified them as persistent.


So the example code for it will be:
static void Main()
{
    SuppressWininetBehavior();

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

[System.Runtime.InteropServices.DllImport("wininet.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetOption(int hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);

private static unsafe void SuppressWininetBehavior()
{
    /* SOURCE: http://msdn.microsoft.com/en-us/library/windows/desktop/aa385328%28v=vs.85%29.aspx
        * INTERNET_OPTION_SUPPRESS_BEHAVIOR (81):
        *      A general purpose option that is used to suppress behaviors on a process-wide basis. 
        *      The lpBuffer parameter of the function must be a pointer to a DWORD containing the specific behavior to suppress. 
        *      This option cannot be queried with InternetQueryOption. 
        *      
        * INTERNET_SUPPRESS_COOKIE_PERSIST (3):
        *      Suppresses the persistence of cookies, even if the server has specified them as persistent.
        *      Version:  Requires Internet Explorer 8.0 or later.
        */

    int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
    int* optionPtr = &option;

    bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
    if (!success)
    {
        MessageBox.Show("Something went wrong !>?");
    }
}

Please make sure your project is allows unsafe code. (under Properties => Build Tab)

This code is deleting the COOKIES per PROCESS on startup ONLY.
[tested on WIN-7 and working great]


Best Regards,
MDB-BLOG :)

Sunday, May 22, 2011

c# WinForm | Check form window size and location

Hello,


I wanted to open a new window form, exactly near another form. (pinning one form to another).
Because of the border difference among Windows XP, Vista and Windows7 (win7), it didn't work easily.

So to determine windows size under win7/vista, I had to check if Windows Aero. (checking made by short&easy code)

Now, after checking this, I had to also support winXP (which does not have AERO technology).

For finding the left and right window border size (width) I used the SystemInformation Class which provides information about the current system environment.

Note:
I recommend to check if it works for other FormBorderStyle.

The code:
internal static bool IsAeroEnabled()
{
    bool isEnabled = false;
    if (Environment.OSVersion.Version.Major >= 6)
    {
        try
        {
            DwmIsCompositionEnabled(out isEnabled);
        }
        catch (Exception ex)
        {
            Logger.WriteLog(ex);
        }
    }
    return isEnabled;
}
[DllImport("dwmapi.dll")]
internal static extern int DwmIsCompositionEnabled(out bool enabled);

Best regard,
MDB Blog

Tuesday, February 1, 2011

C# | Determine if Adobe (Macromedia) Flash player installed.

All started when I needed to integrate an Adobe (Macromedia) Flash object in my C# WinForm application.
I saw several posts about it, where two solutions where presents:
1. Add WebBrowser Control and just nevigate to the "test.swf" file.
2. Create COM object of ADOBE MACROMEDIA.

I liked the 1st option more, because I don't need to handle COM objects (and to add another DLL to the app).
Here is the code I used:
WebBrowser wb = new WebBrowser();
//wb.Location = SOME LOCATION
//wb.Size = SOME SIZE
wb.AllowNavigation = false;
wb.IsWebBrowserContextMenuEnabled = false;
this.Controls.Add(wb); // this = FORM
wb.Navigate(@"C:\test.swf");

BUT, Then i noticed that when a pc do NOT have Adobe (Macromedia) Flash player installed, the webbrowser display a big red X.
SO, before I use the FLASH image in my winform application, I needed to check if FLASH player is INSTALLED or not!

The idea is to check the registry for:
HKEY_LOCAL_MACHINE\SOFTWARE\Macromedia\FlashPlayer\CurrentVersion

And indeed it worked!
Here is the full code for testing if FLASH installed (and also get the major Version):
internal static int? GetFlashPlayerVersion()
{
    using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Macromedia\FlashPlayer"))
    {
        if (rk != null)
        {
            string version = rk.GetValue("CurrentVersion") as string;
            if (string.IsNullOrEmpty(version) == false)
            {
                int idx = version.IndexOf(",");
                if (idx > 0)
                {
                    int value;
                    if (int.TryParse(version.Substring(0, idx), out value) == true)
                    {
                        return value;
                    }
                }
            }
        }
    }
    return null;
}

And the code which using the method:
int? flashVersion = WindowsUtils.GetFlashPlayerVersion();
if (flashVersion.HasValue == true && flashVersion > 6)
{
    WebBrowser wb = new WebBrowser();
    wb.AllowNavigation = false;
    wb.IsWebBrowserContextMenuEnabled = false;
    this.Controls.Add(wb); // this = FORM
    wb.Navigate(@"C:\test.swf");
}

Best regards,
MDB-Blog

Monday, October 4, 2010

Trim Image white-spaces (black&white) | C# Winforms

I searched for a simple code that preform "TRIMMING" to an image.
By "trimming" i mean, that if i have a LARGE image that contains information (painting/drawing...) only in small part of the image and all other is white-space (WHITE or BLACK pixels).

I needed to remove such whitespace and also to decrease image size.
Following three code examples:

Code #1 - Gets the NON-WHITE-SPACE bounds of an image
private Rectangle GetImageNonWhiteSpaceBounds(Bitmap p_img, bool p_isBlackWhitespace)
{
    Rectangle rect = new Rectangle();
    unsafe
    {
        BitmapData bdActual = null;
        try
        {
            int width = p_img.Width;
            int height = p_img.Height;

            bdActual = p_img.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            Int32 i;
            Int32 pSize = 3;
            Byte whiteTrashold = (Byte)240;
            Byte blackTrashold = (Byte)10;
            Byte* sourceRow;

            Int32 minX = width;
            Int32 maxX = 0;
            Int32 minY = height;
            Int32 maxY = 0;
            bool isWhitepace;

            for (Int32 _y = 0; _y < height; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 for (Int32 _x = 0; _x < width; ++_x)                 {                     i = _x * pSize;                     isWhitepace =                         (p_isBlackWhitespace && sourceRow[i] <= blackTrashold && sourceRow[i + 1] <= blackTrashold && sourceRow[i + 2] <= blackTrashold)                         ||                         (!p_isBlackWhitespace && sourceRow[i] >= whiteTrashold && sourceRow[i + 1] >= whiteTrashold && sourceRow[i + 2] >= whiteTrashold);

                    if (isWhitepace == false)
                    {
                        // NO whitespace!!!
                        minX = Math.Min(_x, minX);
                        maxX = Math.Max(_x, maxX);

                        minY = Math.Min(_y, minY);
                        maxY = Math.Max(_y, maxY);
                    }
                }
            }

            rect.X = minX;
            rect.Y = minY;
            rect.Width = maxX - minX;
            rect.Height = maxY - minY;
        }
        finally
        {
            if (bdActual != null)
            {
                p_img.UnlockBits(bdActual);
            }
        }
    }
    return rect;
}

Code #2 - Draw rectangle around the NON-WHITE-SPACE
private void DrawNonWhiteSpaceRectangle(Bitmap p_img, bool p_isBlackWhitespace, Color p_color)
{
    unsafe
    {
        BitmapData bdActual = null;
        try
        {
            int width = p_img.Width;
            int height = p_img.Height;

            bdActual = p_img.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            Int32 i;
            Int32 pSize = 3;
            Byte whiteTrashold = (Byte)240;
            Byte blackTrashold = (Byte)10;
            Byte* sourceRow;

            Int32 minX = width;
            Int32 maxX = 0;
            Int32 minY = height;
            Int32 maxY = 0;
            bool isWhitepace;

            for (Int32 _y = 0; _y < height; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 for (Int32 _x = 0; _x < width; ++_x)                 {                     i = _x * pSize;                     isWhitepace =                         (p_isBlackWhitespace && sourceRow[i] <= blackTrashold && sourceRow[i + 1] <= blackTrashold && sourceRow[i + 2] <= blackTrashold)                         ||                         (!p_isBlackWhitespace && sourceRow[i] >= whiteTrashold && sourceRow[i + 1] >= whiteTrashold && sourceRow[i + 2] >= whiteTrashold);

                    if (isWhitepace == false)
                    {
                        // NO whitespace!!!
                        minX = Math.Min(_x, minX);
                        maxX = Math.Max(_x, maxX);

                        minY = Math.Min(_y, minY);
                        maxY = Math.Max(_y, maxY);
                    }
                }
            }

            // draw rectagle:
            for (Int32 _y = minY; _y <= maxY; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 i = minX * pSize;                 sourceRow[i] = (Byte)p_color.R;                 sourceRow[i + 1] = (Byte)p_color.G;                 sourceRow[i + 2] = (Byte)p_color.B;                 i = maxX * pSize;                 sourceRow[i] = (Byte)p_color.R;                 sourceRow[i + 1] = (Byte)p_color.G;                 sourceRow[i + 2] = (Byte)p_color.B;             }             Byte* sourceRowX1 = (Byte*)bdActual.Scan0 + (minY * bdActual.Stride);             Byte* sourceRowX2 = (Byte*)bdActual.Scan0 + (maxY * bdActual.Stride);             for (Int32 _x = minX; _x <= maxX; ++_x)             {                 i = _x * pSize;                 sourceRowX1[i] = (Byte)p_color.R;                 sourceRowX1[i + 1] = (Byte)p_color.G;                 sourceRowX1[i + 2] = (Byte)p_color.B;                 sourceRowX2[i] = (Byte)p_color.R;                 sourceRowX2[i + 1] = (Byte)p_color.G;                 sourceRowX2[i + 2] = (Byte)p_color.B;             }         }         finally         {             if (bdActual != null)             {                 p_img.UnlockBits(bdActual);             }         }     } }


Code #3 - Trim Image whitespaces
private Bitmap CropImageWhitespaces(Bitmap p_img, bool p_isBlackWhitespace)
{
    Rectangle rect = new Rectangle();
    unsafe
    {
        BitmapData bdActual = null;
        try
        {
            int width = p_img.Width;
            int height = p_img.Height;

            bdActual = p_img.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            Int32 i;
            Int32 pSize = 3;
            Byte whiteTrashold = (Byte)240;
            Byte blackTrashold = (Byte)10;
            Byte* sourceRow;

            Int32 minX = width;
            Int32 maxX = 0;
            Int32 minY = height;
            Int32 maxY = 0;
            bool isWhitepace;

            for (Int32 _y = 0; _y < height; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 for (Int32 _x = 0; _x < width; ++_x)                 {                     i = _x * pSize;                     isWhitepace =                         (p_isBlackWhitespace && sourceRow[i] <= blackTrashold && sourceRow[i + 1] <= blackTrashold && sourceRow[i + 2] <= blackTrashold)                         ||                         (!p_isBlackWhitespace && sourceRow[i] >= whiteTrashold && sourceRow[i + 1] >= whiteTrashold && sourceRow[i + 2] >= whiteTrashold);

                    if (isWhitepace == false)
                    {
                        // NO whitespace!!!
                        minX = Math.Min(_x, minX);
                        maxX = Math.Max(_x, maxX);

                        minY = Math.Min(_y, minY);
                        maxY = Math.Max(_y, maxY);
                    }
                }
            }

            rect.X = minX;
            rect.Y = minY;
            rect.Width = maxX - minX;
            rect.Height = maxY - minY;
        }
        finally
        {
            if (bdActual != null)
            {
                p_img.UnlockBits(bdActual);
            }
        }
    }

    return p_img.Clone(rect, p_img.PixelFormat);
}

I hope it will be helpful for you.
this code if fast and easy to use.