Home » excel » c# – Checking whether focus is set to excel cell

c# – Checking whether focus is set to excel cell

Posted by: admin March 9, 2020 Leave a comment

Questions:

I am working on VSTO Project. I need to detect the input focus in Excel vsto project.

I want to check whether focus is on excel cell or it is on other excel component like find dialog, document action pane or any other excel built-in dialog.

Is this possible to detect?

Please refer screen shot

As shown in screen shot, I want to know whether input focus is set to excel cell or not?

How to&Answers:

This will get the title of the active window (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

It will return the title on the active window, but I assume a length of 100 characters will be enough.

This code should give a function that returns the current title, and correctly adjust for length. (I currently do not have c# installed, so I can’t test this):

[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();
}

You should then be able to test the string to see what it contains. In the VBA example, entering =ActiveWindowName() into A1 returns Microsoft Excel - Book1

Answer:

You need to do something like this :

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;
}