How to hide the TextBox caret in .NETCF

I was trying to help a developer today in the smart device forums who wanted to hide the caret in the TextBox control. I started playing around with the Windows Mobile Platform SDK and I stumbled upon the methods HideCaret() and ShowCaret().

The outcome is this simple inherited TextBox control I decided to call TextBoxWithoutCaret :)

class TextBoxWithoutCaret : TextBox
{
    [DllImport("coredll.dll")]
    static extern bool HideCaret(IntPtr hwnd);
 
    [DllImport("coredll.dll")]
    static extern bool ShowCaret(IntPtr hwnd);
 
    protected override void OnGotFocus(EventArgs e)
    {
        base.OnGotFocus(e);
        HideCaret(Handle);
    }
 
    protected override void OnLostFocus(EventArgs e)
    {
        base.OnLostFocus(e);
        ShowCaret(Handle);
    }
}

Every time the TextBox control is focused I hide the caret and enable it again when focus is lost. This doesn't really make much practical sense and the only reason I do this is because HideCaret() is described to perform a cumulative operation meaning ShowCaret() must be called the same number of times HideCaret() was called for the caret to be visible again.



Resizing an Image in .NETCF

I've seen some people ask how to resize an image or how to stretch an image in .NET Compact Framework in the community. Although the operation is pretty simple, I'll share a code snippet anyway.

public static Image Resize(Image image, Size size)
{
    Image bmp = new Bitmap(size.Width, size.Height);
    using (var g = Graphics.FromImage(bmp))
    {
        g.DrawImage(
            image,
            new Rectangle(0, 0, size.Width, size.Height),
            new Rectangle(0, 0, image.Width, image.Height),
            GraphicsUnit.Pixel);
    }
    return bmp;
}

What the code above does is to create a new image with the specified new size and draw the source image to fit the new image.



Improve .NETCF Build Performance in Visual Studio

A lot of .NETCF developers are surprisingly not aware of the Platform Verification Task in Visual Studio. Disabling this in the build process will speed up the build of .NETCF projects. To make things quick and short, here's what you need to do:

1) Open the file C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.CompactFramework.Common.targets for editing.

2) Change the following:

   99   <Target
  100     Name="PlatformVerificationTask">
  101     <PlatformVerificationTask
  102       PlatformFamilyName="$(PlatformFamilyName)"
  103       PlatformID="$(PlatformID)"
  104       SourceAssembly="@(IntermediateAssembly)"
  105       ReferencePath="@(ReferencePath)"
  106       TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
  107       PlatformVersion="$(TargetFrameworkVersion)"/>
  108   </Target>


to:

   99   <Target
  100     Name="PlatformVerificationTask">
  101     <PlatformVerificationTask
  102       Condition="'$(DoPlatformVerificationTask)'=='true'"
  103       PlatformFamilyName="$(PlatformFamilyName)"
  104       PlatformID="$(PlatformID)"
  105       SourceAssembly="@(IntermediateAssembly)"
  106       ReferencePath="@(ReferencePath)"
  107       TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
  108       PlatformVersion="$(TargetFrameworkVersion)"/>
  109   </Target>


The following configuration above was an excert from an article called Platform Verification Task leading to slow builds on compact framework projects



Generic Singleton Implementation

Here's a helpful class that I've been using for implementing singleton objects through the years. This way I can use any class (as long as it has a default constructor) as a singleton object. Originally, I called this class the YetAnotherSingleton< T > but that was simply too unprofessional and I ended up renaming it.

public static class Singleton<T> where T : class, new()
{
    private static readonly object staticLock = new object();
    private static T instance;
 
    public static T GetInstance()
    {
        lock (staticLock)
        {
            if (instance == null)
                instance = new T();
            return instance;
        }
    }
 
    public static void Dispose()
    {
        if (instance == null)
            return;
        var disposable = instance as IDisposable;
        if (disposable != null)
            disposable.Dispose();
        instance = null;
    }
}

And here's an example of how to use the class above. To improve performance of web service calls its a good idea to use a singleton instance of the web service proxy class.

public static class ServiceClientFactory
{
    public static Service GetService()
    {
        var ws = Singleton<Service>.GetInstance();
        ws.Url = ConfigurationManager.AppSettings["ServiceUrl"];
        ws.Credentials = GetCredentials();
        return ws;
    }
 
    private static ICredentials GetCredentials()
    {
        var username = ConfigurationManager.AppSettings["ServiceUsername"];
        var password = ConfigurationManager.AppSettings["ServicePassword"];
        var domain = ConfigurationManager.AppSettings["ServiceDomain"];
        return new NetworkCredential(username, password, domain);
    }
}


In my next few articles I'll be sharing code from my design pattern framework that I've been using through the years.



ListView Background Image in .NETCF

In this short entry I'd like to demonstrate how to display a background image in the ListView control. For this we will send the LVM_SETBKIMAGE or the LVM_GETBKIMAGE message to the ListView control with the LVBKIMAGE struct as the LPARAM. Unfortunately, the Windows CE version of LVBKIMAGE does not support LVBKIF_SOURCE_URL flag which allows using an image file on the file system for the background image of the ListView.

The layout of the background image can be either tiled or specified by an offset percentage. The background image is not affected by custom drawing, unless of course you decide to fill each sub item rectangle. For setting the background image we use the LVBKIF_SOURCE_HBITMAP flag together with the layout which is either LVBKIF_STYLE_TILE or LVBKIF_STYLE_NORMAL. If we set the layout to LVBKIF_STYLE_NORMAL, then we have the option of setting where the image will be drawn by setting the value of xOffsetPercentage and yOffsetPercentage.

In this example I'd like to make use of extension methods to add the SetBackgroundImage() and GetBackgroundImage() methods to ListView. This can of course be easily used to in a property to an inherited ListView.

public static class ListViewExtensions
{
    [DllImport("coredll")]
    static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, ref LVBKIMAGE lParam);
 
    const int LVM_FIRST = 0x1000;
    const int LVM_SETBKIMAGE = (LVM_FIRST + 138);
    const int LVM_GETBKIMAGE = (LVM_FIRST + 139);
    const int LVBKIF_SOURCE_NONE = 0x00000000;
    const int LVBKIF_SOURCE_HBITMAP = 0x00000001;
    const int LVBKIF_STYLE_TILE = 0x00000010;
    const int LVBKIF_STYLE_NORMAL = 0x00000000;
 
    struct LVBKIMAGE
    {
        public int ulFlags;
        public IntPtr hbm;
        public IntPtr pszImage; // not supported
        public int cchImageMax;
        public int xOffsetPercent;
        public int yOffsetPercent;
    }
 
    public static void SetBackgroundImage(this ListView listView, Bitmap bitmap)
    {
        SetBackgroundImage(listView, bitmap, false);
    }
 
    public static void SetBackgroundImage(this ListView listView, Bitmap bitmap, bool tileLayout)
    {
        SetBackgroundImage(listView, bitmap, tileLayout, 0, 0);
    }
 
    public static void SetBackgroundImage(
        this ListView listView,
        Bitmap bitmap,
        bool tileLayout,
        int xOffsetPercent,
        int yOffsetPercent)
    {
        LVBKIMAGE lvBkImage = new LVBKIMAGE();
        if (bitmap == null)
            lvBkImage.ulFlags = LVBKIF_SOURCE_NONE;
        else
        {
            lvBkImage.ulFlags = LVBKIF_SOURCE_HBITMAP | (tileLayout ? LVBKIF_STYLE_TILE : LVBKIF_STYLE_NORMAL);
            lvBkImage.hbm = bitmap.GetHbitmap();
            lvBkImage.xOffsetPercent = xOffsetPercent;
            lvBkImage.yOffsetPercent = yOffsetPercent;
        }
 
        SendMessage(listView.Handle, LVM_SETBKIMAGE, 0, ref lvBkImage);
    }
 
    public static Bitmap GetBackgroundImage(this ListView listView)
    {
        LVBKIMAGE lvBkImage = new LVBKIMAGE();
        lvBkImage.ulFlags = LVBKIF_SOURCE_HBITMAP;
 
        SendMessage(listView.Handle, LVM_GETBKIMAGE, 0, ref lvBkImage);
 
        if (lvBkImage.hbm == IntPtr.Zero)
            return null;
        else
            return Bitmap.FromHbitmap(lvBkImage.hbm);
    }
}

Here's an example of exposing the background image as a property in an inherited ListView by using the extension methods above.

class ListViewEx : ListView
{
    public Bitmap BackgroundImage
    {
        get { return this.GetBackgroundImage(); }
        set { this.SetBackgroundImage(value, BackgroundLayout == BackgroundImageLayout.Tile); }
    }
 
    public BackgroundImageLayout BackgroundLayout { get; set; }
 
    public enum BackgroundImageLayout
    {
        Tile,
        Center
    }
}

A small catch with the ListView background image is that it is only supported in Windows CE 5.0 and later. Hope you found this information useful.