10

我开发了一个小型应用程序C# .NET来操作 excel 表,我不知道为什么有些用户一直告诉我,当他们打开 excel 文件时,尽管我将可见设置为 true,但窗口并没有出现在前面/顶部状态最大化。

这是读取excel文件的函数:

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

有任何想法吗 ?

4

6 回答 6

9

一些魔法,对我有用:

app.WindowState = XlWindowState.xlMinimized; // -4140
app.WindowState = XlWindowState.xlMaximized; // -4137
于 2016-04-19T12:10:29.133 回答
7

我发现这行得通。 如何将 Excel 应用程序置于最前面

[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);
}
于 2014-07-24T16:00:27.000 回答
5

我会尝试通过

app.ActiveWindow.Activate();

如果这不起作用,您可能会在 http://social.msdn.microsoft.com/ 的此线程中找到其他解决方案(涉及本机 WinAPI 调用)

于 2013-10-01T18:10:51.143 回答
3

有时如果在 Excel 中同时打开多个文件,ActiveWindow.Activate()将无法正常工作。

一个成功的技巧是先最小化然后最大化命令。

于 2014-04-06T16:28:12.223 回答
2

我知道有点晚了,但为什么需要使用 FindWindow,Windows 句柄可以通过 Application 访问:

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

public static void BringExcelWindowToFront(Application xlApp)
{
   SetForegroundWindow((IntPtr)xlApp.Hwnd);  // Note Hwnd is declared as int
}

如果多个窗口具有相同的标题,则不会有任何问题。

于 2015-05-27T08:50:54.967 回答
0

要激活特定工作簿:

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

  public static void BringExcelWindowToFront(Excel._Workbook xlBook)
  {
     var windows = xlBook.Windows;
     foreach (Excel.Window window in windows)
     {
        IntPtr handler = (IntPtr)window.Hwnd;

        SetForegroundWindow(handler);
        return;
     }
  }
于 2019-09-03T22:14:04.920 回答