84 lines
3.2 KiB
C#
84 lines
3.2 KiB
C#
using System;
|
|
using System.Diagnostics;
|
|
using System.Runtime.InteropServices;
|
|
using System.Windows.Forms;
|
|
|
|
namespace Workplace
|
|
{
|
|
public static class Utils
|
|
{
|
|
[DllImport("user32.dll")]
|
|
static extern bool SetForegroundWindow(IntPtr hWnd, string formName);
|
|
[DllImport("user32.dll")]
|
|
private static extern IntPtr GetForegroundWindow();
|
|
[DllImport("user32.dll")]
|
|
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
|
|
[DllImport("user32.dll")]
|
|
private static extern bool SetForegroundWindow(IntPtr hWnd);
|
|
[DllImport("user32.dll")]
|
|
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
|
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
|
|
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
|
|
|
|
|
|
private const int ALT = 0xA4;
|
|
private const int EXTENDEDKEY = 0x1;
|
|
private const int KEYUP = 0x2;
|
|
private const int SHOW_MAXIMIZED = 3;
|
|
|
|
public static bool Activate(string windowClassName)
|
|
{
|
|
IntPtr hWnd = FindWindow(windowClassName, null); // this gives you the handle of the window you need.
|
|
|
|
// then use this handle to bring the window to focus or forground(I guessed you wanted this).
|
|
|
|
// sometimes the window may be minimized and the setforground function cannot bring it to focus so:
|
|
|
|
/*use this ShowWindow(IntPtr handle, int nCmdShow);
|
|
*there are various values of nCmdShow 3, 5 ,9. What 9 does is:
|
|
*Activates and displays the window. If the window is minimized or maximized, *the system restores it to its original size and position. An application *should specify this flag when restoring a minimized window */
|
|
|
|
ShowWindow(hWnd, 9);
|
|
//The bring the application to focus
|
|
SetForegroundWindow(hWnd);
|
|
|
|
return true;
|
|
|
|
|
|
//try
|
|
//{
|
|
// //This is the same as the name of the executable without the .exe at the end
|
|
// Process[] processes = Process.GetProcessesByName(processName);
|
|
// if (processes.Length >= 1)
|
|
// {
|
|
// ActivateWindow(processes[0].MainWindowHandle);
|
|
// return true;
|
|
// }
|
|
// return false;
|
|
//}
|
|
//catch (Exception e)
|
|
//{
|
|
// return false;
|
|
//}
|
|
}
|
|
|
|
//public static void ActivateWindow(IntPtr mainWindowHandle)
|
|
//{
|
|
// // Guard: check if window already has focus.
|
|
// if (mainWindowHandle == GetForegroundWindow()) return;
|
|
|
|
// // Show window maximized.
|
|
// ShowWindow(mainWindowHandle, SHOW_MAXIMIZED);
|
|
|
|
// // Simulate an "ALT" key press.
|
|
// keybd_event((byte)ALT, 0x45, EXTENDEDKEY | 0, 0);
|
|
|
|
// // Simulate an "ALT" key release.
|
|
// keybd_event((byte)ALT, 0x45, EXTENDEDKEY | KEYUP, 0);
|
|
|
|
// // Show window in forground.
|
|
// SetForegroundWindow(mainWindowHandle);
|
|
//}
|
|
}
|
|
}
|