首页 > 解决方案 > SendKeys 并不总是通过 ProcessId 将密钥宏发送到 AppActivate 到另一个进程

问题描述

任务:编写一个程序,在单击时仅显示 3 个按钮,模拟在另一个窗口中按下组合键(宏 Ctrl+Z)。

我做了什么:我的代码:

Public Class Form1
    Dim FigmaWindowName As String
    Dim Processes

    Public Sub New()
        'init form
        InitializeComponent()

        'set top position
        TopMost = True


    End Sub

    Private Sub ButtonUndo_Click(sender As Object, e As EventArgs) Handles ButtonUndo.Click

        Processes = GetObject("winmgmts:").InstancesOf("Win32_Process")

        For Each Process In Processes
            If StrComp(Process.Name, "Figma.exe", vbTextCompare) = 0 Then

                ' Activate the window using its process ID...
                With CreateObject("WScript.Shell")
                    .AppActivate(Process.ProcessId)
                    .SendKeys("(^z)")

                End With

                ' We found our process. No more iteration required...
                Exit For

            End If
        Next

        '....other buttons
    End Sub
End Class

问题:不稳定。如果它不起作用,则单击时两个窗口都会闪烁,并且组合键不会发送到其他应用程序。https://www.loom.com/share/89c47dfa38bc4bb6b1d3ff8b97b84ac8

问题我做错了什么?

标签: vbavb.netvisual-studiovisual-studio-2019sendkeys

解决方案


首先,我不相信存在与“发送密钥”一起使用的稳定应用程序。但是,如果这是进行自动化的唯一方法,请对您的代码进行一些额外的检查。

Dim wShell = CreateObject("WScript.Shell")

Dim isWindowActive As Boolean = False
Do 
    'AppActivate will return true when window is really active'
    isWindowActive = wShell.AppActivate(Process.ProcessId) 
    WScript.Sleep 100
Loop Until isWindowActive 
wShell.sendKeys("(^z)")

推荐阅读