gpt4 book ai didi

c# - ContextMenuStrip.Show 一半时间不工作

转载 作者:行者123 更新时间:2023-12-04 08:10:48 26 4
gpt4 key购买 nike

tl/dr:我第二次调用 ContextMenuStrip.Show 时,它不显示。
我正在构建一个在后台运行但在用户点击特定热键时在鼠标光标上显示下拉菜单的应用程序。
如果应用程序具有焦点,则这在 100% 的时间内都有效。如果另一个应用程序有焦点(这是我的主要用例),它恰好有 50% 的时间失败。具体来说,第一次按下热键有效,但是一旦您从菜单中选择了一个项目(触发了一个简短的功能),下一次按下热键就不会显示菜单。如果不单击菜单一直按热键,则菜单会在光标位置不断弹出。如果您切换回应用程序,则每次都会出现该菜单。
我对编码相当陌生,但我已经简化了代码,这样热键按下只会运行一行代码(ContextMenuStrip.Show),并且我已经在调试器和 中进行了观察。那条线确实被击中 ,在我看来,所有变量在工作和不工作的打印机上都是一样的。
编辑:这是我可以制作的代码的最简单版本。请原谅任何奇怪的事情。我是编码新手,可能正在做不相关的奇怪事情!
要重现,运行程序,切换到另一个窗口,按 Ctl-Q 调出菜单,选择一个项目,再次按 Ctl-Q,菜单应该无法显示。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;
using System.Runtime.InteropServices;

namespace Bug
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Register hotkey
int UniqueHotkeyId = 1;
int HotKeyCode = (int)Keys.Q;
Boolean F9Registered = RegisterHotKey(
this.Handle, UniqueHotkeyId, 2, HotKeyCode
);
myPopupMenu.menu = myPopupMenu.BuildMenu();
}
// Stuff that makes the hotkey work
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

protected override void WndProc(ref Message m)
{
// Catch when a HotKey is pressed !
if (m.Msg == 0x0312)
{
int id = m.WParam.ToInt32();
if (id == 1)
{
// Show Menu on hoteky press
myPopupMenu.ShowMenu();
}
}
base.WndProc(ref m);
}
public PopupMenu myPopupMenu = new PopupMenu();
}


public class PopupMenu
{
public ContextMenuStrip menu { get; set; }

public ContextMenuStrip BuildMenu()
{
ContextMenuStrip menu = new ContextMenuStrip();
ToolStripMenuItem item;
ToolStripMenuItem submenu;

submenu = new ToolStripMenuItem();
submenu.Text = "submenu";

item = new ToolStripMenuItem("item", null, MenuClick);
submenu.DropDownItems.Add(item);
menu.Items.Add(submenu);

return menu;
}

public void ShowMenu()
{
menu.Show(Cursor.Position);
}

public void MenuClick(object sender, EventArgs e) { }
}
}

最佳答案

改变

ContextMenuStrip menu = new ContextMenuStrip();
ContextMenuStrip menu = new ContextMenuStrip { AutoClose = false };
你的例子现在在我这边 100% 的时间都有效(专注和不专注)。
为什么,我不太确定。只是使用自动化工具快速改变事物,直到发生所需的行为。

关于c# - ContextMenuStrip.Show 一半时间不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65972785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com