in focus not returned to the active sheet
I have developed an excel add-in (VSTO) in c# and that has a task pane with tree view in it. When I click the tree view it loads some data to excel sheet. But after loading the focus still remains on the tree view so that i cant directly type on in the cell without clicking on the sheet. I need to take the focus to active work sheet as soon as the sheet is populate upon the click of the tree view. I tried following methods but no luck
ActiveSheet.Select()
ActiveSheet.Activate()
And i tried setting the range as well. One other thing is that when I add a break point to the ActiveSheet.Activate()
it works after hitting the break point but without that it still keeps the focus on the task pane.
After trying hard I found a simple solution
SendKeys.Send("{F1}");
This simply solved my problem. But yet strange because actually F2 is the proper key but it doesn't work. Only F1 works.
The SendKeys.Send("{F1}") approach didn't work for me. I think that what is happening is that we are trying to activate a window that thinks it is already activated, except that it's not fully activated.
So, we need to activate another window to ensure that Excel gets properly deactivated, then reactivate Excel. But, we don't want the user to see any flickering or weirdness. The approach that worked for me was to:
[DllImport("user32.dll")]
public static extern int GetDesktopWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
SetForegroundWindow(GetDesktopWindow());
SetForegroundWindow(excelHandle);
对于任何使用Add-in Express创建Excel加载项的人,都可以使用ADXKeyFilter
事件并将缺省处理程序参数的Action
属性设置为ADXKeyFilterAction.SendToHostApplication
。
上一篇: 在Excel VSTO中用C#压缩“存储为文本的数字”警告
下一篇: 焦点不会返回到活动工作表