Skip to content

Instantly share code, notes, and snippets.

@blue7wings
Last active April 4, 2019 03:04
Show Gist options
  • Select an option

  • Save blue7wings/e7c72c905b07e006735ecffccc97266b to your computer and use it in GitHub Desktop.

Select an option

Save blue7wings/e7c72c905b07e006735ecffccc97266b to your computer and use it in GitHub Desktop.
bring app to front
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace AppToFront
{
class Program
{
[DllImport("USER32.DLL")]
static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
[DllImport("USER32.DLL")]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
//Definition for Window Placement Structure
[StructLayout(LayoutKind.Sequential)]
private struct WINDOWPLACEMENT
{
public int length;
public int flags;
public int showCmd;
public System.Drawing.Point ptMinPosition;
public System.Drawing.Point ptMaxPosition;
public System.Drawing.Rectangle rcNormalPosition;
}
//Definitions For Different Window Placement Constants
const UInt32 SW_HIDE = 0;
const UInt32 SW_SHOWNORMAL = 1;
const UInt32 SW_NORMAL = 1;
const UInt32 SW_SHOWMINIMIZED = 2;
const UInt32 SW_SHOWMAXIMIZED = 3;
const UInt32 SW_MAXIMIZE = 3;
const UInt32 SW_SHOWNOACTIVATE = 4;
const UInt32 SW_SHOW = 5;
const UInt32 SW_MINIMIZE = 6;
const UInt32 SW_SHOWMINNOACTIVE = 7;
const UInt32 SW_SHOWNA = 8;
const UInt32 SW_RESTORE = 9;
public static void BringFont(string name)
{
//Checks if application is running
try
{
Process process = Process.GetProcessesByName(name)[0];
if (process != null)
{
bool status = process.WaitForInputIdle(1000);
Console.WriteLine(status);
IntPtr s = process.MainWindowHandle;
WINDOWPLACEMENT param = new WINDOWPLACEMENT();
param.length = Marshal.SizeOf(typeof(WINDOWPLACEMENT));
GetWindowPlacement(s, ref param);
Console.WriteLine(param.showCmd);
if (param.showCmd == 1 || param.showCmd == 3)
{
SetForegroundWindow(s);
}
else
{
param.showCmd = 1;
SetWindowPlacement(s, ref param);
}
}
}
catch (Exception exc)
{
Console.WriteLine("ERROR: Application is not running!\nException: " + exc.Message);
Console.ReadKey();
return;
}
}
static void Main(string[] args)
{
BringFont("chrome");
Console.WriteLine("start");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment