Use a bitmap for an icon in C#

[icon]

You can’t set a form’s Icon property equal to a bitmap. Fortunately it’s easy enough to create an icon from a bitmap.

This example uses the following code to make a form’s icon display the image in a bitmap.

// Convert the bitmap resource to an icon and use it.
private void Form1_Load(object sender, EventArgs e)
{
    // Get the bitmap.
    Bitmap bm = new Bitmap(Properties.Resources.Spiral);

    // Convert to an icon and use for the form's icon.
    this.Icon = Icon.FromHandle(bm.GetHicon());
}

The program gets the bitmap stored in its Spiral resource. It then uses the bitmap’s GetHicon method to get a handle to an icon holding the same image. It passes the handle to the Icon class’s FromHandle method to create an Icon object and sets the form’s Icon property equal to the result.

Note that the GetHicon method creates an icon in unmanaged memory. If the form stops using the icon, its memory is not freed. If you only create a few icons in this way, that’s no big deal, but if the program makes hundreds of icons at run time, this may result in a memory leak. If you need to create and destroy many icons at run time, use the DestroyIcon API function to free the icon handle’s memory.

Note also that the system may need to display the form’s icon in many sizes. For example, it may display different sizes in the form’s upper left corner, in the Alt-Tab task switcher, and the task bar. Because an icon created from a bitmap only has one size, it will be scaled as needed and the results may not look very good. To get better results, build a real icon file and include all of the sizes that the system might need.


Download Example   Follow me on Twitter   RSS feed   Donate




Posted in forms, graphics, image processing | Tagged , , , , , , , , , , | Leave a comment

Make a tool that creates PNG files with transparent backgrounds in C#

[transparent]

When you use the File menu’s Open command, the following code lets you select a image file.

// The image.
private Bitmap Bm = null;

// Offset for displaying the image.
private const int Offset = 10;

// Open a file.
private void mnuFileOpen_Click(object sender, EventArgs e)
{
    if (ofdFile.ShowDialog() == DialogResult.OK)
    {
        try
        {
            Bm = new Bitmap(ofdFile.FileName);
            picImage.ClientSize = new Size(
                Bm.Width + 2 * Offset,
                Bm.Height + 2 * Offset);
            picImage.Visible = true;
            picImage.Refresh();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

This code displays an OpenFileDialog. If the user selects a file and clicks Open, the code sets Bm to a new Bitmap created from the file.

The program then sizes the picImage PictureBox control to fit the Bitmap plus a margin. When the code then refreshes the PictureBox, the following Paint event handler executes.

// Draw the picture.
private void picImage_Paint(object sender, PaintEventArgs e)
{
    if (Bm == null) return;
    e.Graphics.DrawImage(Bm, Offset, Offset);
}

At design time, I set the PictureBox control’s background image to the blue cloud design shown in the picture. The Paint event handler draws the Bitmap on top of the PictureBox, leaving a margin around the picture so you can see the background.

If you click on the picture, the following code makes the pixels with the clicked color transparent.

// Set the transparent pixel.
private void picImage_MouseClick(object sender, MouseEventArgs e)
{
    // Get the color clicked.
    Color color = Bm.GetPixel(e.X - Offset, e.Y - Offset);

    // Make that color transparent.
    Bm.MakeTransparent(color);

    // Show the result.
    picImage.Refresh();
}

This code uses the Bitmap class’s GetPixel method to get the color of the clicked pixel. It then calls the Bitmap object’s MakeTransparent method to make all pixels of that color transparent. Finally the code refreshes the PictureBox so you can see the image with its newly transparent pixels.

The last piece of the program executes when you select the File menu’s Save command.

// Save the file.
private void mnuFileSave_Click(object sender, EventArgs e)
{
    if (sfdFile.ShowDialog() == DialogResult.OK)
    {
        try
        {
            Bm.Save(sfdFile.FileName, ImageFormat.Png);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

This code displays a SaveFileDialog. If the user selects a file name and clicks Save, the program calls the Bitmap object’s Save method, passing it the parameter Png to indicate that it should save the Bitmap in a PNG file.

The program only saves in the PNG format because that’s the only format it can use that saves transparent pixels. (It also provides decent compression.)

Note that image formats such as GIF and most JPGs sometimes smoothly shade areas that should be solid color so if you load them into this program, you may have trouble clicking on all of the pixels that you want to make transparent.


Download Example   Follow me on Twitter   RSS feed   Donate




Posted in graphics, image processing | Tagged , , , , , , , , , , , , , | Leave a comment

Give an image a transparent background in C#

[transparent]

The Bitmap class’s MakeTransparent method changes all of the pixels with a given color to the transparent color A = 0, R = 0, G = 0, B = 0. When the program starts, the following code makes the background transparent for the two images stored in the program’s Smile and Frown resources.

// The images.
private Bitmap SmileBitmap, FrownBitmap;

// Make the images' backgrounds transparent.
private void Form1_Load(object sender, EventArgs e)
{
    SmileBitmap = Properties.Resources.Smile;
    SmileBitmap.MakeTransparent(SmileBitmap.GetPixel(0, 0));

    FrownBitmap = Properties.Resources.Frown;
    FrownBitmap.MakeTransparent(FrownBitmap.GetPixel(0, 0));
}

The code saves the Smile resource in a Bitmap variable. It then uses the Bitmap object’s MakeTransparent method to make all of its pixels that match the color of the pixel in the upper left corner transparent. The code then repeats those steps for the Frown image.

The following Paint event handler displays the two images.

// Draw the two images overlapping.
private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawImage(FrownBitmap, 30, 30);
    e.Graphics.DrawImage(SmileBitmap, 95, 85);
}

This code simply draws the two images overlapping so you can see that they have transparent backgrounds.


Download Example   Follow me on Twitter   RSS feed   Donate




Posted in graphics, image processing | Tagged , , , , , , , , , , , , | Leave a comment

Make a TextBox convert text into proper case in C#

[proper case]

The example Convert a string to proper case (title case) in C# uses a CultureInfo object’s TextInfo property to convert text into proper case (or title case). There are a couple of tricks and potential problems that you need to know about if you want to use that technique to make a TextBox convert its contents into proper case.

One approach would be to intercept key strokes and convert the typed characters to create a proper case result. That’s trickier than you might think. In particular, dealing with the user pressing Ctrl+X and Ctrl+V to cut or paste text in the TextBox is quite confusing.

Another strategy would be to catch the TextBox control’s TextChanged event and convert the text into proper case there. That event fires after text is cut or pasted so you have the final text easily available. That approach works but there’s another issue to consider: where the user’s focus is. After you change the text to proper case, you need to restore the focus to where it was before you changed the control’s text.

This example uses the following TextChanged event handler to convert text into proper case.

// Convert the TextBox's text into proper case.
private void TextBoxToProperCase(TextBox txt)
{
    // Save the selection's start and length.
    int sel_start = txt.SelectionStart;
    int sel_length = txt.SelectionLength;

    CultureInfo culture_info =
        Thread.CurrentThread.CurrentCulture;
    TextInfo text_info = culture_info.TextInfo;
    txt.Text = text_info.ToTitleCase(txt.Text);

    // Restore the selection's start and length.
    txt.Select(sel_start, sel_length);
}

This code saves the TextBox control’s current selection position and length. It then converts the control’s text to proper case and restores the original selection position and length. The result is quite good, although you still have the same drawbacks given by the CultureInfo object’s TextInfo property. In particular, it doesn’t handle some odd cases such as VBScript and O’Dell.


Download Example   Follow me on Twitter   RSS feed   Donate




Posted in controls, strings | Tagged , , , , , , , , , , , , , | Leave a comment

Five hats puzzle solution

[hats puzzle]

If you haven’t read it yet, read the Five hats puzzle.

Recall that the warden has three white hats and two black hats. If the first prisoner, Art, saw two black hats, then he would know that he had a white hat. Art says he doesn’t know his hat color, so the other two prisoners must be wearing either at least one white hat.

Next if Billy saw Carter wearing a black hat, he would know that he (Billy) was wearing a white hat (because they are wearing at least one white hat). Billy says he can’t tell which color hat he is wearing, so that means Carter must be wearing a white hat.

Now Carter knows that he must be wearing a white hat so he says that he knows his hat color. (He’s not called “Clever Carter” for nothing.)

My the book Interview Puzzles Dissected not only describes similar hats puzzles (and lots of other kinds of puzzles) and their solutions, but it also discusses extensions to the puzzles. For example:

  • What happens if Art can guess his hat color?
  • What if there was only one black hat?
  • What if there was no penalty for guessing incorrectly?
  • What if there were four prisoners? How many black and white hats would you need for the last prisoner to figure out his hat color? Could the second-to-last prisoner figure out his color?


Follow me on Twitter   RSS feed   Donate


Posted in books, games, puzzles | Tagged , , , , , , , , , , , | Leave a comment

Five hats puzzle

[hats puzzle]

This “hats puzzle” was described on December 26, 2016 on NPR’s Car Talk show. Sadly Tommy died in 2014 and the show was a rebroadcast so this puzzler has probably been used before.

My book Interview Puzzles Dissected doesn’t include this puzzle but it does include some other similar hats puzzles so this one can give you some of the flavor of those puzzles. The following version is my modified version of the puzzle, but the logic is the same.

A sadistic jailer plays a little game with new inmates. When a new prisoner arrives, he gathers that person and the two inmates who have been incarcerated the longest and blindfolds them. He then places a hat on each of their heads. He has three white hats and two black hats.

Next the jailer places the prisoners in a line so each can only see the hats of those in front of him. In this case the new prisoner, Art (three years for jaywalking), is first so he can see both of the other prisoners’ hats. Next comes Billy “The Blade” (seven years for failing to signal a lane change) who can only see the third prisoner. Last comes Clever Carter (three months for self-dealing millions of dollars from a charity) who can see no one.

If a prisoner correctly guesses his hat color, he gets a year off of his sentence. If he guesses incorrectly, he adds two years to his sentence. If he doesn’t guess at all, his sentence remains unchanged.

The warden asks Art what he thinks and Art replies, “I don’t know.”

Next the warden asks Billy who also says, “I don’t know, either.”

Finally the warden asks Carter who answers, “I know my hat color!”

What color is Carter’s hat?

Try to work it out and then follow this link to see the solution.


Follow me on Twitter   RSS feed   Donate




Posted in books, games, puzzles | Tagged , , , , , , , , , , | Leave a comment

Convert a string to proper case (title case) in C#

[proper case]

In proper case (or title case) the first letter of each word is capitalized. This is actually pretty easy once you know where to find the method that converts to proper case.

The example uses the following code to convert the string in the variable txt into proper case.

// Convert to proper case.
CultureInfo culture_info = Thread.CurrentThread.CurrentCulture;
TextInfo text_info = culture_info.TextInfo;
txt = text_info.ToTitleCase(txt);

The code creates a CultureInfo object representing the program’s current culture. (This uses the System.Globalization and System.Threading namespaces.) It gets the culture’s TextInfo object and calls its ToTitleCase method to convert the text to proper case.

Note that this method isn’t perfect. For example, it will keep a string in all caps such as NASA in all caps but it won’t preserve odd mixed case examples such as VBScript. It also doesn’t consider an apostrophe to be the start of a new word so, for example, it would capitalize the name O’Dell as O’dell. Those are odd cases, however, and I wouldn’t expect it to handle every case perfectly.


Download Example   Follow me on Twitter   RSS feed   Donate


Posted in strings | Tagged , , , , , , , , , , , | Leave a comment

Make TextBoxes automatically convert case in C#

[example]

It’s actually quite easy to make a TextBox convert case in .NET. Simply set the TextBox control’s CharacterCasing property to Lower or Upper. Then the control automatically converts alphabetic characters into the correct case.

You can do this at design time, although in this example I set the properties in the following code so they are easy to see.

private void Form1_Load(object sender, EventArgs e)
{
    txtLowerCase.CharacterCasing = CharacterCasing.Lower;
    txtUpperCase.CharacterCasing = CharacterCasing.Upper;
}

That’s all there is to making a TextBox convert case, at least to upper and lower case. My next two posts will look at proper case, where each word in a phrase is capitalized.


Download Example   Follow me on Twitter   RSS feed   Donate




Posted in controls, strings, user interface | Tagged , , , , , , , , , , , , | Leave a comment

See if Internet Explorer uses a proxy in C#

[proxy]

This example determines whether the system has Internet Explorer configured to use a proxy.

Internet Explorer lets you specify proxy settings. In the Tools menu, select Internet Options. On the Connections tab, click the LAN Settings button.

[proxy]
The goal of this example is to figure out if the box indicated by the arrow in the picture on the right is checked.


The IsInternetProxyEnabled method shown in the following code returns true if the box is checked.

// Return True if the internet settings has ProxyEnable = true.
private bool IsInternetProxyEnabled()
{
    // See if Internet Explorer uses a proxy.
    RegistryKey key =
        Registry.CurrentUser.OpenSubKey(
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings");
    string[] keys = key.GetValueNames();
    bool result = (int)key.GetValue("ProxyEnable", 0) != 0;
    key.Close();

    return result;
}

The method looks at the Registry key HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings. If the value of ProxyEnable is not 0, then the box is checked and the method returns true.

The way this works changes with each release, presumably to make you think something is new and improved, so I don’t know if this works with the latest browser Microsoft Edge. To get to its proxy settings:

  • Click the ellipsis (…) in the upper right
  • Select Settings
  • Scroll down and click View Advanced Settings
  • Open Proxy Settings
  • Click Open Proxy Settings

If you try it in Edge, please post your results in the comments below.


Download Example   Follow me on Twitter   RSS feed   Donate




Posted in internet, network, system | Tagged , , , , , , , , , , | Leave a comment

Move a window with a title that matches a pattern in C#

[example]

The example Set another application’s size and position in C# uses the FindWindow API function to find a window with a given title. Unfortunately FindWindow only finds the window if the title is an exact match. If you only know part of the title or if there are extra spaces or other characters in the title, FindWindow won’t find it.

This example enumerates the desktop windows and looks for one with a title that matches a regular expression. The following code shows how the FindWindowTitleMatch method starts the process.

// The target window's pattern to match
// and the found handle and title.
private static string MatchPattern;
private static IntPtr MatchedHandle;
private static string MatchedTitle;

// Return a list of the desktop windows' handles and titles.
public static void FindWindowTitleMatch(
   string pattern, out IntPtr handle, out string title)
{
    MatchPattern = pattern;
    MatchedHandle = IntPtr.Zero;
    MatchedTitle = "";

    EnumDesktopWindows(IntPtr.Zero, FilterCallback, IntPtr.Zero);

    handle = MatchedHandle;
    title = MatchedTitle;
}

The FindWindowTitleMatch method saves the pattern that it should match in the MatchPattern variable. It also initializes the MatchedHandle and MatchedTitle values to defaults that it will return if it cannot find a matching window.

The method then calls the EnumDesktopWindows method passing it the FilterCallback method as the method that the API function should call for each of the windows that it enumerates.

After EnumDesktopWindows finishes, the program copies the values contained in the MatchedHandle and MatchedTitle variables into the method’s return variables.

The following code shows the FilterCallback method that is called by the EnumDesktopWindows API function.

// Select the first window that matches the target pattern.
private static bool FilterCallback(IntPtr hWnd, int lParam)
{
    // Get the window's title.
    StringBuilder sb_title = new StringBuilder(1024);
    int length = GetWindowText(hWnd, sb_title, sb_title.Capacity);
    string title = sb_title.ToString();

    // If the window is visible and has a title, see if it matches.
    if (IsWindowVisible(hWnd) &&
        string.IsNullOrEmpty(title) == false)
    {
        if (title.Matches(MatchPattern))
        {
            MatchedHandle = hWnd;
            MatchedTitle = title;
            // Return false to indicate that we
            // don't need to continue enumerating windows.
            return false;
        }
    }

    // Return true to indicate that we
    // should continue enumerating windows.
    return true;
}

The method uses the GetWindowText API function to get the current window’s title. If the window is visible and the title is not blank, the method uses the Matches string extension to determine whether the title matches the target pattern. (For information about the Matches string extension, see Make a string extension to determine whether a string matches a regular expression in C#.)

If the title matches, the method saves its handle and title in the MatchedHandle and MatchedTitle variables and returns false to tell EnumDesktopWindows that it doesn’t need to continue enumerating windows. If the title doesn’t match, the method returns true to tell EnumDesktopWindows that it hasn’t found a match yet and that it should continue enumerating other windows.

After it finds a matching window, the main program uses the SetWindowPlacement method to restore the window so it’s not minimized or maximized. It then uses the SetWindowPosition method to move the window to the desired position.

As in the example Set another application’s size and position in C#, be careful where you move windows. If you move a window off of the screen, you’ll need to use this program or something similar to get it back.

Download the example program to see additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




Posted in API, miscellany, regular expressions, system | Tagged , , , , , , , , , , , , | Leave a comment