Rob Shurman
Rob Shurman

Reputation: 61

Excel AddIn - Keeping windows form always visible while w/in Excel

First of all, thank you for your time and assistance in reviewing this!...

I'm trying to upgrade an Excel VBA workbook to a VSTO Excel Add-in in VB.NET using VS 2010. In the original (i.e.- VBA) version I have a modeless UserForm (called frmMain) that floats on top and is visible at all times while the user is still within the Excel application, but is not visible if the user moves to another window outside of Excel.

For example, within Excel the user can click on any worksheet tab, select any cell, etc. and the UserForm is still visible. This is exactly how I'd like it.

The problem is, that in the new VSTO add-in, I can not get the Windows form to mimic this same behavior.

I use frmMain.Show() to show the form as a modeless form, but the moment the user clicks an Excel worksheet (i.e.- activates a worksheet) the form becomes hidden behind the worksheet.

I can manually Alt-Tab to bring the form back into view, but I need it to always remain in view - floating on top of the Excel worksheets so long as the user hasn't left the Excel application.

I tried various things, including setting the form to TopMost, however, that causes the form to be TopMost everywhere - including outside of Excel. Worse than that, if the user does anything that would normally result in Excel's launching a dialog box (e.g.- closing an open workbook, raising the alert "Do you want to save the changes...") the alert dialog box itself is hidden and inaccessible behind the frmMain form (since the frmMain is TopMost).

How can I get my form to behave in the desired way (i.e.- the same way it did in VBA)?

Thanks!!!

Rob

Upvotes: 6

Views: 1468

Answers (2)

Milad
Milad

Reputation: 127

This method might work (worked for me):

  1. Create a worksheet_selectionChange event handler inside your form class

  2. Put these lines in this event handler:

     Dim FormHandle As IntPtr = Me.Handle
     Me.Visible = False 
     Me.Show(NativeWindow.FromHandle(FormHandle))
    

Upvotes: 0

SliverNinja - MSFT
SliverNinja - MSFT

Reputation: 31641

You should take a look at Custom Task Panes which can be docked or floated within the Excel application. You could also look into the COM interfaces for a lower level connection (see related SO Post) - although Task Panes are really what this type of behavior was intended for.

Upvotes: 1

Related Questions