检查焦点是否设置为excel cell

Tus*_*iya 7 c# excel vba vsto excel-vba

我正在研究VSTO项目.我需要在Excel vsto项目中检测输入焦点.

我想检查焦点是否在excel单元格上,或者它是否在其他excel组件上,如查找对话框,文档操作窗格或任何其他excel内置对话框.

这有可能被发现吗?

请参考截图

如屏幕截图所示,我想知道输入焦点是否设置为excel cell?

Sea*_*anC 3

这将获取活动窗口的标题(vba)

Option Explicit

Private Declare Function GetActiveWindow Lib "User32.dll" () As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long

Function ActiveWindowName()
Dim hWnd As Long
Dim lngRet As Long
Dim strText As String

hWnd = GetActiveWindow()
strText = String(100, Chr(0))
lngRet = GetWindowText(hWnd, strText, 100)
ActiveWindowName=strText
End Function
Run Code Online (Sandbox Code Playgroud)

它将返回活动窗口上的标题,但我认为 100 个字符的长度就足够了。

这段代码应该给出一个返回当前标题的函数,并正确调整长度。(我目前没有安装c#,所以我无法测试这个):

[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();

[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

public static string GetActiveWindowText()
{
    IntPtr hWnd = GetActiveWindow();  
    // Allocate correct string length first
    int length = GetWindowTextLength(hWnd);
    StringBuilder sb = new StringBuilder(length + 1);
    GetWindowText(hWnd, sb, sb.Capacity);
    return sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)

然后您应该能够测试该字符串以查看它包含的内容。在 VBA 示例中,=ActiveWindowName()输入A1返回Microsoft Excel - Book1