Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force to bring excel window to the front?

Tags:

c#

excel

i have a small application developed in C# .NET that manipulate excel sheets, I don't know why some users keep telling me that when they open the excel file the window doesn't appear on front/top although I set the visible to true and the window state on maximized.

This is the function that reads the excel file:

public static void OpenExcel(string fileName, bool visibility, FunctionToExecute fn = null)
{
    string addInPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft\\AddIns\\mDF_XLcalendar.xla");

    deleg = fn;
    app = new Excel.Application();

    app.Workbooks.Open(addInPath);
    app.Workbooks.Open(fileName);

    app.ScreenUpdating = true;
    app.DisplayAlerts = true;
    app.Visible = visibility;
    app.UserControl = true;
    app.WindowState = Excel.XlWindowState.xlMaximized;

    EventDel_BeforeBookClose = new Excel.AppEvents_WorkbookBeforeCloseEventHandler(application_WorkbookBeforeClose);
    EventSave_BeforeBookClose = new Excel.AppEvents_WorkbookBeforeSaveEventHandler(Open_ExcelApp_WorkbookBeforeSave);

    app.WorkbookBeforeClose += EventDel_BeforeBookClose;
    app.WorkbookBeforeSave += EventSave_BeforeBookClose;     
} 

Any ideas ?

like image 271
Nabil Laarif Avatar asked Oct 01 '13 14:10

Nabil Laarif


People also ask

How do I make Excel always on top?

To freeze the top row or first column:From the View tab, Windows Group, click the Freeze Panes drop down arrow. Select either Freeze Top Row or Freeze First Column. Excel inserts a thin line to show you where the frozen pane begins.

How do you change window view in Excel?

To close a Sheet View and return to the default view, select View > Sheet View > Exit. To switch between views, select View > Sheet View, and then select your view from the Sheet View menu.


2 Answers

I found this to work. How to bring an Excel app to the front

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);   

public static void BringExcelWindowToFront(Application xlApp)
{

   string caption = xlApp.Caption;
   IntPtr handler = FindWindow(null, caption);
   SetForegroundWindow(handler);
}
like image 108
Just R Avatar answered Oct 16 '22 07:10

Just R


some magic, that work for me:

app.WindowState = XlWindowState.xlMinimized; // -4140
app.WindowState = XlWindowState.xlMaximized; // -4137
like image 10
ai85l Avatar answered Oct 16 '22 05:10

ai85l