peschuster

Technology, .NET and Web

  • Info

UI

WinForms ListView DoubleClick Event for Empty Lists

January 2, 2014 by peter

The WinForms ListView control fires double click events only if the user clicked on a selected item. This is also documented on the MSDN site: “The mouse pointer must be over a child object (TreeNode or ListViewItem).” (Control.DoubleClick Event).

Sometimes it is useful to perform actions on double click events for empty ListView controls, too.

To achieve this you have to implement a custom ListView control which inherits from the original WinForms ListView control:

using System;
using System.Security.Permissions;
using System.Windows.Forms;

internal class CustomListView : ListView
{
    private const int WM_LBUTTONDBLCLK = 515;

    private bool doubleClickFired;

    protected override void OnDoubleClick(EventArgs e)
    {
        base.OnDoubleClick(e);

        this.doubleClickFired = true;
    }

    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
    protected override void WndProc(ref Message m)
    {
        this.doubleClickFired = false;

        base.WndProc(ref m);

        if (m.Msg == WM_LBUTTONDBLCLK && !this.doubleClickFired)
        {
            this.OnDoubleClick(EventArgs.Empty);
        }
    }
}

This custom control checks whether a double click event was triggered for double clicks of the left mouse button on the control. If this is not the case, it triggers a double click event “manually”.

Posted in: .NET, UI Tagged: .NET, ListView, UI, WndProc

How to add an uac shield icon to a MenuItem

December 8, 2011 by peter

Since Windows Vista an application needs administrator privileges to perform some system operations like starting or stopping a Windows service. To gain these privileges you can add an “app.manifest” file to your project in Visual Studio and set the requestedExecutionLevel to requireAdministrator.

In Windows there is always the small shield icon to inform the user that administrator privileges are required for the desired action:

image

To add this icon to your own context menu in a WinForms project the following steps are required:

1. Check that the user currently has no administrator privileges:

public bool HasAdministratorRights
{
    get
    {
        var pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

        return pricipal != null && pricipal.IsInRole(WindowsBuiltInRole.Administrator);
    }
}

2. Use a ContextMenuStrip and ToolStripMenuItems instead of the old ContextMenu and MenuItems.

3. Import the SHGetStockIconInfo method from shell32:

private static class NativeMethods
{
    [DllImport("Shell32.dll", SetLastError = false)]
    public static extern Int32 SHGetStockIconInfo(SHSTOCKICONID siid, SHGSI uFlags, ref SHSTOCKICONINFO psii);

    public enum SHSTOCKICONID : uint
    {
        SIID_SHIELD = 77
    }

    [Flags]
    public enum SHGSI : uint
    {
        SHGSI_ICON = 0x000000100,
        SHGSI_SMALLICON = 0x000000001
    }

    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct SHSTOCKICONINFO
    {
        public UInt32 cbSize;
        public IntPtr hIcon;
        public Int32 iSysIconIndex;
        public Int32 iIcon;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szPath;
    }
}

4. Fetch the shield icon and create a bitmap out of the HIcon:

private void SetUacShield(ToolStripMenuItem menuItem)
{
    NativeMethods.SHSTOCKICONINFO iconResult = new NativeMethods.SHSTOCKICONINFO();
    iconResult.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(iconResult);

    NativeMethods.SHGetStockIconInfo(
        NativeMethods.SHSTOCKICONID.SIID_SHIELD, 
        NativeMethods.SHGSI.SHGSI_ICON | NativeMethods.SHGSI.SHGSI_SMALLICON, 
        ref iconResult);

    menuItem.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
    menuItem.Image = Bitmap.FromHicon(iconResult.hIcon);
}

That’s all. Now you can restart you application with administrator rights or call another executable with the “runas” verb:

private void RunAsAdmin(string fileName, string args)
{
    var processInfo = new ProcessStartInfo
    {
        Verb = "runas",
        FileName = fileName,
        Arguments = args,
    };

    try
    {
        Process.Start(processInfo);
    }
    catch (Win32Exception)
    {
        // Do nothing...
    }
}
Posted in: .NET, UI Tagged: .NET, UAC, UI, WinForms

Syndication

  • RSS 2.0

Recent Posts

  • Ubiquiti EdgeRouter™ X SFP – Teardown
  • Force HttpWebRequest to IPv4
  • Blackmagic Design ATEM GPI and Tally Interface Teardown
  • WinForms ListView DoubleClick Event for Empty Lists
  • Planning Center Online – Custom Plan Reports in Landscape Orientation

Tags

.NET AntiXssEncoder ASP.NET Build c# Configuration crawler Debugging EF ELMAH Expression tree Graphite Interop IssuerNameRegistry iTunes Linq ListView MVC pco pdf Security SecurityKey SecurityToken simulatebe sql server StatsD STS teardown TYPO3 UAC UI UserSettings Visual Studio WIF WIF in depth WinForms WndProc
profile for Peter at Stack Overflow, Q&A for professional and enthusiast programmers Peter Schuster

Copyright © 2023 peschuster.

Alpha WordPress Theme by themehall.com