//************************************************************************
// author: yuzhengyang
// date: 2018.3.27 - 2018.6.3
// desc: 工具描述
// Copyright (c) yuzhengyang. All rights reserved.
//************************************************************************
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace Azylee.Core.WindowsUtils.APIUtils
{
public class WindowsAPI
{
#region 系统空闲时间
#region 捕获时间结构体
[StructLayout(LayoutKind.Sequential)]
struct LASTINPUTINFO
{
// 设置结构体块容量
[MarshalAs(UnmanagedType.U4)]
public int cbSize;
// 捕获的时间
[MarshalAs(UnmanagedType.U4)]
public uint dwTime;
}
#endregion
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
///
/// 获取计算机无操作时间
///
///
public static long GetLastInputTime()
{
long time = 0;
try
{
LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo);
// 捕获时间
if (!GetLastInputInfo(ref vLastInputInfo)) time = 0;
else time = Environment.TickCount - (long)vLastInputInfo.dwTime;
}
catch { }
return time > 0 ? time : 0;
}
#endregion
///
/// 获取当前窗口句柄
///
///
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();
///
/// 显示窗口
///
///
/// 0关闭 1正常显示 2最小化 3最大化
///
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
///
/// 获取窗口大小
///
///
///
///
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
#region 窗口大小结构体
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; //最左坐标
public int Top; //最上坐标
public int Right; //最右坐标
public int Bottom; //最下坐标
}
#endregion
///
/// 获取窗口所在进程ID
///
///
///
///
[DllImport("user32", EntryPoint = "GetWindowThreadProcessId")]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int pid);
///
/// 获取窗体标题
///
///
///
///
///
[DllImport("user32.dll")]
public extern static int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
///
/// 当前窗口标题
///
///
public static string GetNowWindowName()
{
StringBuilder windowName = new StringBuilder(GetWindowTextLength(GetForegroundWindow()) + 1);
GetWindowText(GetForegroundWindow(), windowName, windowName.Capacity);
return windowName.ToString() ?? "";
}
///
/// 当前窗口进程名
///
///
public static string GetNowProcessName()
{
int windowPid = 0;
GetWindowThreadProcessId(GetForegroundWindow(), out windowPid);
string processName = Process.GetProcessById(windowPid).ProcessName;
return processName ?? "";
}
}
}