WPF's ContextMenu causes memory leak in ctfmon.exe

黎庆文 0 Reputation points
2025-09-25T10:47:20.7966667+00:00

Hi. In WPF, if the control right clicks and creates a new ContextMenu every time, too many times can lead to memory leaks in ctfmon.exe
Here is my example code:
private void TestButton_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)

{

if (e.RightButton == System.Windows.Input.MouseButtonState.Pressed)

{

if (contextMenu != null && contextMenu.IsOpen)

{

contextMenu.IsOpen = false;

contextMenu = null;

}

contextMenu = new ContextMenu();

MenuItem menuItem = new MenuItem { Header = "Test Menu Item" };

menuItem.Click += (s, args) => MessageBox.Show("Menu Item Clicked");

contextMenu.Items.Add(menuItem);

contextMenu.IsOpen = true;

contextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;

}

}

I use the mouse click tool to simulate right clicking with the mouse, clicking ten times per second. The memory of ctfmon.exe will increase by about 1MB per minute.
Does anyone know the reason for this? It's very important to me.

Developer technologies | Windows Presentation Foundation
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Le (WICLOUD CORPORATION) 3,495 Reputation points Microsoft External Staff
    2025-09-26T07:01:23.7066667+00:00

    Hello 黎庆文,

    Thank you for reaching out.

    Creating a new ContextMenu for every single right-click seems inefficient.

    Each time you create a new ContextMenu, it allocates not just managed memory in your app, but also unmanaged resources within these Windows services.

    When you create and destroy menus very quickly, the system can't clean up these resources fast enough. This leads to a gradual memory buildup in ctfmon.exe.

    The best practice is to create a single ContextMenu once and reuse it.

    I hope this helps. If my answer is useful, please consider marking it as final.

    Thank you.

    1 person found this answer helpful.

  2. Starry Night 600 Reputation points
    2025-09-29T02:57:44.8633333+00:00

    Is there any way to check the usage of the desktop heap in Windows?

    You can use Debugger Commands !heap extension to display heap usage information, control breakpoints in the heap manager, detect leaked heap blocks, search for heap blocks, or display page heap information.

    This extension supports the segment heap and the NT heap. Use !heap with no parameter to list all heaps and their type.

    You can also use Desktop Heap Diagnostic Tool to help diagnose Desktop Heap Exhaustion issues. DesktopHeapDiag can probe the various Desktop Heaps and display their current usage %.

    Hope it can help you.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.