无法激活Excel窗口

时间:2013-11-21 17:09:15

标签: c# asp.net office-interop

Excel窗口保持最小化。如何将它带到浏览器的前面。

using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;

protected void btnOpen_Click(object sender, EventArgs e)
{
  OpenExcel();
}

private void OpenExcel()
{
  Excel.Application app = new Excel.Application();
  Excel.Workbook wb = null;
  Excel.Worksheet ws = null;
  Excel.Range range = null;

  app.visible = true;
  wb = app.Workbooks.Add(1);
   ws = (Excel.Worksheet)wb.WorkSheets[1];
   range = ws.get_Range("A1","D1");

   ws.Cells[1,1]="Date";
   ws.Cells[1,2]="Code";
   ws.Cells[1,3]="Name";
   app.WindowState = Excel.XlWindowState.xlNormal;     
   app.ActiveWindow.Activate();
}

1 个答案:

答案 0 :(得分:3)

为了保证这一点,根据我的经验,我必须做以下事情:

if (app.WindowState == XlWindowState.xlMinimized)
{
    app.WindowState = XlWindowState.xlNormal;
}
app.WindowState = XlWindowState.xlMaximized;
app.ShowWindowsInTaskbar = true;
app.Visible = true;

IntPtr hwnd = new IntPtr(app.Hwnd);
Win32Helper.SetForegroundWindow(hwnd);

SetForegroundWindow是interop

[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);