gpt4 book ai didi

.net - 当窗体没有焦点时激活 ContextMenuStrip

转载 作者:行者123 更新时间:2023-12-05 00:31:30 27 4
gpt4 key购买 nike

  1. 我能够在 Windows 窗体外成功显示 ContextMenuScript (CMS)。
  2. 我可以使用鼠标指针选择/单击项目。
  3. 但是,当表单未获得焦点时,它不喜欢键盘控制(向上/向下箭头、转义)。
  4. 如果表单获得焦点并显示 CMS,则键盘可以控制它,但在未获得焦点时不能控制 :(。
  5. 我需要有关代码的帮助,这将有助于在不关注形式的情况下实现这一目标。

问候

   Public Const CTRL_Key As Integer = &H2
Public Const Hot_Key As Integer = &H312
Public Declare Function RegisterHotKey Lib "user32" (ByVal hwnd As IntPtr, ByVal id As Integer, ByVal fsModifiers As Integer, ByVal vk As Integer) As Integer
Public Declare Function UnregisterHotKey Lib "user32" (ByVal hwnd As IntPtr, ByVal id As Integer) As Integer

Private Sub Hot_Key_Register() Handles MyBase.Load
RegisterHotKey(Me.Handle, 100, CTRL_Key, Keys.NumPad1)
RegisterHotKey(Me.Handle, 200, CTRL_Key, Keys.NumPad2)
RegisterHotKey(Me.Handle, 300, CTRL_Key, Keys.NumPad3)
End Sub

Protected Overrides Sub WndProc(ByRef Window_Message As Message)

If Window_Message.Msg = Hot_Key Then
Dim id As IntPtr = Window_Message.WParam
Select Case (id.ToString)
Case "100"
CMS_01.Show(Cursor.Position.X, Cursor.Position.Y)
Case "200"
CMS_02.Show(Cursor.Position.X, Cursor.Position.Y)
Case "300"
CMS_03.Show(Cursor.Position.X, Cursor.Position.Y)
End Select
End If
MyBase.WndProc(Window_Message)
End Sub

最佳答案

选项 1 - 使用 NotifyIcon

您可以使用的最简单的修复方法是使用不可见的 NotifyIcon组件在其内部处理这种情况 code .

NotifyIcon 的实例拖放到您的表单上,然后使用它来显示上下文菜单,将上下文菜单条分配给它的 ContextMenuStrip属性,然后使用反射调用其 ShowContextMenu 私有(private)方法。

示例

Private Sub ShowContextMenu(menu As ContextMenuStrip)
NotifyIcon1.Visible = False
NotifyIcon1.ContextMenuStrip = menu
Dim m = NotifyIcon1.GetType().GetMethod("ShowContextMenu",
Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
m.Invoke(NotifyIcon1, Nothing)
End Sub
Protected Overrides Sub WndProc(ByRef Window_Message As Message)
If Window_Message.Msg = Hot_Key Then
Dim id As IntPtr = Window_Message.WParam
Select Case (id.ToString)
Case "100"
ShowContextMenu(CMS_01)
End Select
End If
MyBase.WndProc(Window_Message)
End Sub

选项 2 - 使用 native 窗口

这是不使用 NotifyIcon 的修复方法, 使用 NativeWindow .下面这段代码关心事件​​窗口,如果当前窗体处于事件状态,则不使用 native 窗口,否则创建并使用 native 窗口。

示例

Private window As NativeWindow
Private Sub ShowContextMenu(menu As ContextMenuStrip, p As Point)
If (Form.ActiveForm IsNot Me) Then
If (window Is Nothing) Then
window = New NativeWindow()
window.CreateHandle(New CreateParams())
End If
SetForegroundWindow(window.Handle)
End If
menu.Show(p)
End Sub

并显示菜单:

ShowContextMenu(CMS_01, Cursor.Position)

请记住在关闭/处理表单时释放窗口句柄:

If (window IsNot Nothing) Then
window.DestroyHandle()
window = Nothing
End If

关于.net - 当窗体没有焦点时激活 ContextMenuStrip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53896842/

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