How to initiate a LabelEdit on a TreeView control in C#

Windows.Forms has a simple TreeView control built around the standard windows Common Control. It supports inline Label editing by setting the LabelEdit property to true. This causes the TreeView control to respond to mouse clicks and present an edit field. However there doesn’t appear to be an easy way of initiating label edits via alternate methods. For example by pressing F2 or using a context menu.

What to do? Use the Win32 API.

The following code snippet triggers treeview label editing.


namespace TreeViewExample {
  public sealed class TreeViewMessages   {
    public const uint TV_FIRST = 0x1100;
    public const uint TVM_EDITLABELA = (TV_FIRST + 14);
    public const uint TVM_EDITLABELW = (TV_FIRST + 65);
  }

  public class Win32 {
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    private static extern IntPtr SendMessage(
      HandleRef hWnd, uint Msg, IntPtr wParam, HandleRef lParam);
  }

  public class TreeViewUtils {
    public static void StartLabelEdit(TreeView treeView, TreeNode node) {
      IntPtr result = Win32.SendMessage(
        new HandleRef(treeView, treeView.Handle),
        TreeViewMessages.TVM_EDITLABELA,
        IntPtr.Zero,
        new HandleRef(node, node.Handle));

      if (result == IntPtr.Zero)
      {
        throw new Exception("Failed to send EDITLABEL message to TreeView control.");
      }
    }
  }
}

Advertisements

6 thoughts on “How to initiate a LabelEdit on a TreeView control in C#

  1. In .NET 2.0, there is the BeginEdit() function for the treeview.

    I put it under a KeyDown for F2 and it works fine. It is being rather stubborn about a call from my context menu. It seems to appear for an instant and then vanish by itself.

    .. Time for extreme measures(putting it back in editing mode, if Enter wasn’t pressed)

  2. Alright, so it wasn’t that easy. If I don’t let it exit without an enter when I call BeginEdit from my context menu, it just flickers for a second or two, and then breaks out of labeledit 🙂

  3. Thanks for the heads up. I’ve found it now. It’s on TreeNode.

    Though I find TreeView too limited so I use TreeViewAdv (see SF.net or CodeProject.com) for most of my complex TreeView controls. It is a good MVC based Tree control.

  4. If you have set LabelEdit to false, you must leave the method StartLabelEdit() bevore SendMessage(). Otherwise an error occurre.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s