检查焦点是否设置为excel单元格

我正在研究VSTO项目。 我需要在Excel vsto项目中检测input焦点。

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

这有可能发现吗?

请参阅截图

如屏幕截图所示,我想知道input焦点是否设置为excel单元格?

这将得到活动窗口的标题(使用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 

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

这段代码应该提供一个返回当前标题的函数,并正确调整长度。 (我目前没有安装C#,所以我不能testing这个):

 [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 hWind = GetActiveWindow(); // Allocate correct string length first int length = GetWindowTextLength(hWnd); StringBuilder sb = new StringBuilder(length + 1); GetWindowText(hWnd, sb, sb.Capacity); return sb.ToString(); } 

然后,您应该能够testingstring以查看它包含的内容。 在VBA示例中,input=ActiveWindowName()A1返回Microsoft Excel - Book1

你需要做这样的事情:

 private bool CheckInputisinExcelCell() { Microsoft.Office.Core.CommandBarControl cmdEdited; cmdEdited=YourExcelApplicationobject.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, 23, System.Reflection.Missing.Value, System.Reflection.Missing.Value); return cmdEdited.Enabled; }