C#调用系统API

在Windows平台,可以利用很多系统API,而在.net平台下用C#调用系统API是比较方便而且也是比较轻松的事情。
我们可以利用C#调用API实现底层驱动程序驱动某一个部件(如串口通讯)和或者外设进行工作,也可以利用系统API实现图形化GUI功能
系统API一般分为:核心级(kernel32.dll),用户级(User32.dll), 应用级(gdi32.dll)和其他一些外设驱动等.
下面我们来看一个简单例子,用系统API获取窗口句柄。

代码


public class User32API

{

private static Hashtable processWnd = null;

public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);

static User32API()

{

if (processWnd == null)

{

processWnd
= new Hashtable();

}

}

[DllImport(
"user32.dll", EntryPoint = "EnumWindows", SetLastError = true)]

public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);

[DllImport(
"user32.dll", EntryPoint = "GetParent", SetLastError = true)]

public static extern IntPtr GetParent(IntPtr hWnd);

[DllImport(
"user32.dll", EntryPoint = "GetWindowThreadProcessId")]

public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);

[DllImport(
"user32.dll", EntryPoint = "IsWindow")]

public static extern bool IsWindow(IntPtr hWnd);

[DllImport(
"kernel32.dll", EntryPoint = "SetLastError")]

public static extern void SetLastError(uint dwErrCode);

[DllImport(
"User32.dll", EntryPoint = "SendMessage")]

private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

Process[] processes;

const int WM_CLOSE = 0x0010;

public void GetCurrentWindowHandle()

{

Microsoft.Win32.RegistryKey oRegistryKey
= Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Amada Software");

string[] subKeys = oRegistryKey.GetSubKeyNames();

IntPtr ptrWnd
= IntPtr.Zero;

foreach (string subkey in subKeys)

{

processes
= Process.GetProcessesByName(subkey);

foreach (Process proc in processes)

{

uint uiPid = (uint)proc.Id;

object objWnd = processWnd[uiPid];

if (objWnd != null)

{

ptrWnd
= (IntPtr)objWnd;

if (ptrWnd != IntPtr.Zero && IsWindow(ptrWnd))

{

SendMessage(ptrWnd, WM_CLOSE,
0, 0);

}

else

{

ptrWnd
= IntPtr.Zero;

}

}

bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), uiPid);

if (!bResult && Marshal.GetLastWin32Error() == 0)

{

objWnd
= processWnd[uiPid];

if (objWnd != null)

{

ptrWnd
= (IntPtr)objWnd;

SendMessage(ptrWnd, WM_CLOSE,
0, 0);

}

}

}

}

}

private static bool EnumWindowsProc(IntPtr hwnd, uint lParam)

{

uint uiPid = 0;

if (GetParent(hwnd) == IntPtr.Zero)

{

GetWindowThreadProcessId(hwnd,
ref uiPid);

if (uiPid == lParam)

{

processWnd[uiPid]
= hwnd;

SetLastError(
0);

return false;

}

}

return true;

}

}
原文地址:https://www.cnblogs.com/cgli/p/1922208.html