How do I open maximized internet explorer? - c#

I have to open maximized internet explorer using C#. I have tried the following:
try
{
var IE = new SHDocVw.InternetExplorer();
object URL = "http://localhost/client.html";
IE.ToolBar = 0;
IE.StatusBar = true;
IE.MenuBar = true;
IE.AddressBar = true;
IE.Width = System.Windows.Forms.SystemInformation.VirtualScreen.Width;
IE.Height = System.Windows.Forms.SystemInformation.VirtualScreen.Height;
IE.Visible = true;
IE.Navigate2(ref URL);
ieOpened = true;
break;
}
catch (Exception)
{
}
I can open with different sizes, but I couldn't find how to open maximized IE. I have checked the msdn, there is no property to for maximize.
Please give me some suggestions.
PS: I am developing C# console application, .Net4.5, and VS2012

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Maximize_IE
{
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static void Main(string[] args)
{
var IE = new SHDocVw.InternetExplorer();
object URL = "http://google.com/";
IE.ToolBar = 0;
IE.StatusBar = true;
IE.MenuBar = true;
IE.AddressBar = true;
IE.Visible = true;
ShowWindow((IntPtr)IE.HWND, 3);
IE.Navigate2(ref URL);
//ieOpened = true;
}
}
}

I would use the process method.
You could start any executable and
It has a property which starts your process maximized
ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
startInfo.WindowStyle = ProcessWindowStyle.Maximized;
startInfo.Arguments = "www.google.com";
Process.Start(startInfo);

Quick google of "csharp maximize SHDocVw window" gives this example:
[DllImport ("user32.dll")]
private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
private const int SW_MAXIMISE = 3;
public void OpenWindow()
{
SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer(); //Instantiate the class.
ShowWindow((IntPtr)ie.HWND, SW_MAXIMISE); //Maximise the window.
ie.Visible = true; //Set the window to visible.
}

try this:
var proc = new Process
{
StartInfo = {
UseShellExecute = true,
FileName = "http://localhost/client.html",
WindowStyle = ProcessWindowStyle.Maximized
}
};
proc.Start();

Related

Bring process to focus c# (ASP.net)

I have created a web application that will call a window based application using:
#region Process
public static string shell_exec(string path, string args)
{
var p = new ProcessStartInfo();
// Redirect the output stream of the child process.
p.UseShellExecute = false;
p.LoadUserProfile = true;
p.RedirectStandardOutput = true;
p.FileName = path;
p.Arguments = args;
p.WindowStyle = ProcessWindowStyle.Normal;
var pc = Process.Start(p);
WindowHelper.BringProcessToFront(pc);
string output = pc.StandardOutput.ReadToEnd();
pc.WaitForExit();
return output;
}
#endregion
this is published using IIS Express server, the process.start() calls the application and shows in the top most (obviously because i set the property topmost true) but not in the taskbar (didn't activate the load event or not focused)
I also used bringprocesstofront function but didn't do anything:
const int SW_RESTORE = 9;
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr handle);
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool ShowWindow(IntPtr handle, int nCmdShow);
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool IsIconic(IntPtr handle);
public static void BringProcessToFront(Process process)
{
IntPtr handle = process.MainWindowHandle;
if (IsIconic(handle))
{
ShowWindow(handle, SW_RESTORE);
}
SetForegroundWindow(handle);
}
am i missing something in my code?
The external process im calling is an application that will register a persons fingerprint (using DPFP digital persona, creating it in window based unless there is for web or javascript)

COM Interop error 0x80010108 (RPC_E_DISCONNECTED) when using winforms

I am using WinForm application to open a new IE browser with height and width and I got below exception:
System.Runtime.InteropServices.COMException (0x80010108): The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED))
And the code it seems to be referencing:
[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);
dynamic ie = Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application");
string URL = "https://www.google.com/";
ie.ToolBar = 0;
ie.StatusBar = false;
ie.MenuBar = false;
ie.Width = 800;
ie.Height = 550;
ie.Visible = true;
ie.Resizable = false;
ie.AddressBar = false;
ie.Visible = true;
ie.Top = 230;
ie.Left = 300;
ie.Navigate(URL);
SetForegroundWindow(ie.Hwnd)
Any ideas please?

Getting output of elevaed exe

I'm writing a c# program that should ran a proccess and print the output to the console or file.
But the exe I want to run must run as admin. I saw that to run an exe as admin i need to set useShellExecute to true. but to enable output redirection i need to set it to false.
What can i do to achieve both?
Thank you!
In this code I get the error printed to the console (because UseShellExecute=false ),
and when changed to true - the program stops.
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = false;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = "aaa.exe";
proc.RedirectStandardError = true;
proc.RedirectStandardOutput = true;
proc.Verb = "runas";
Process p = new Process();
p.StartInfo = proc;
p.Start();
while (!p.StandardOutput.EndOfStream)
{
string line = p.StandardOutput.ReadLine();
Console.WriteLine("*************");
Console.WriteLine(line);
}
You could try something like this:
#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
#endregion
namespace CSUACSelfElevation
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// Update the Self-elevate button to show a UAC shield icon.
this.btnElevate.FlatStyle = FlatStyle.System;
SendMessage(btnElevate.Handle, BCM_SETSHIELD, 0, (IntPtr)1);
}
[DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
static extern int SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, IntPtr lParam);
const UInt32 BCM_SETSHIELD = 0x160C;
private void btnElevate_Click(object sender, EventArgs e)
{
// Launch itself as administrator
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Application.ExecutablePath;
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
// The user refused to allow privileges elevation.
// Do nothing and return directly ...
return;
}
Application.Exit(); // Quit itself
}
}
}

Security context of a new process started from windows service C#

I have a windows service that runs under a logon say "UserA". The job of the windows service is to start a new process on a timer elapsed event.
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Task.Factory.StartNew(() => StartNewProcess());
}
private void Initialize()
{
newProcess = new Process();
newProcess.StartInfo.FileName = "Test.exe";
newProcess.StartInfo.Arguments = "sessionId...";
newProcess.StartInfo.CreateNoWindow = false;
newProcess.StartInfo.ErrorDialog = false;
newProcess.StartInfo.RedirectStandardError = true;
newProcess.StartInfo.RedirectStandardInput = true;
newProcess.StartInfo.UseShellExecute = false;
newProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
}
private void StartNewProcess()
{
newProcess.Start();
}
On task manager I see that both the windows service and the new process have a "User Name" as "UserA".
But the problem is Windows service is able to access "C:\QueryResult" but the new process is not able to access "C:\QueryResult"
I am using File.Copy("C:\QueryResult", "D:\blahblah") on both the process
Has the security context changed in the new process?
Try automatically elevating the application permissions like so:
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Windows.Forms;
public static class Program
{
[STAThread]
public static void Main()
{
if (!IsAdmin() && IsWindowsVistaOrHigher())
RestartElevated();
else
DoStuff();
}
private static Boolean IsAdmin()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity != null)
return (new WindowsPrincipal(identity)).IsInRole(WindowsBuiltInRole.Administrator);
return false;
}
private static Boolean IsWindowsVistaOrHigher()
{
OperatingSystem os = Environment.OSVersion;
return ((os.Platform == PlatformID.Win32NT) && (os.Version.Major >= 6));
}
private static void RestartElevated()
{
String[] argumentsArray = Environment.GetCommandLineArgs();
String argumentsLine = String.Empty;
for (Int32 i = 1; i < argumentsArray.Length; ++i)
argumentsLine += "\"" + argumentsArray[i] + "\" ";
ProcessStartInfo info = new ProcessStartInfo();
info.Arguments = argumentsLine.TrimEnd();
info.CreateNoWindow = false;
info.ErrorDialog = false;
info.FileName = Application.ExecutablePath;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.UseShellExecute = false;
info.Verb = "runas";
info.WindowStyle = ProcessWindowStyle.Hidden;
info.WorkingDirectory = Environment.CurrentDirectory;
try
{
Process.Start(info);
}
catch { return; }
Application.Exit();
}
}

Opening a process in C# with hidden window

I have a function for starting processes on a local machine:
public int StartProcess(string processName, string commandLineArgs = null)
{
Process process = new Process();
process.StartInfo.FileName = processName;
process.StartInfo.Arguments = commandLineArgs;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.ErrorDialog = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
return process.Id;
}
It is supposed to start the process without opening a new window. Indeed, when I test it with timeout.exe no console window is opened. But when I test it with notepad.exe or calc.exe their windows still open.
I saw online that this method works for other people. I'm using .NET 4.0 on Windows 7 x64.
What am I doing wrong?
The CreateNoWindow flag applies to Console processes only.
See here for the details:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx
Secondly applications can ignore the WindowStyle argument - it has effect the first time the new application calls ShowWindow, but subsequent calls are under the control of the application.
Following program will show/hide the window:
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
const int SW_SHOW = 5;
static void Main()
{
// The 2nd argument should be the title of window you want to hide.
IntPtr hWnd = FindWindow(null, "Untitled - Notepad");
if (hWnd != IntPtr.Zero)
{
//ShowWindow(hWnd, SW_SHOW);
ShowWindow(hWnd, SW_HIDE); // Hide the window
}
}
}
Source: http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/1bc7dee4-bf1a-4c41-802e-b25941e50fd9
You need to remove the process.StartInfo.UseShellExecute = false
public int StartProcess(string processName, string commandLineArgs = null)
{
Process process = new Process();
process.StartInfo.FileName = processName;
process.StartInfo.Arguments = commandLineArgs;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.ErrorDialog = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
return process.Id;
}

Categories