C#中使用User32.dll的常见用法示例
发布人:shili8
发布时间:2024-11-19 04:34
阅读次数:0
**使用 User32.dll 的 C# 示例**
`User32.dll` 是 Windows API 中的一个重要库,提供了许多用于操作系统交互的函数。C# 程序员可以通过 P/Invoke(Platform Invoke)技术在 C# 中调用这些函数。下面是一些常见用法示例。
###1. 获取当前窗口句柄`GetForegroundWindow()` 函数返回当前激活的窗口的句柄。
csharpusing System;
using System.Runtime.InteropServices;
class Program{
[DllImport("User32.dll")]
static extern IntPtr GetForegroundWindow();
static void Main()
{
IntPtr hwnd = GetForegroundWindow();
Console.WriteLine(hwnd);
}
}
###2. 获取窗口标题`GetWindowText()` 函数返回指定窗口的标题。
csharpusing System;
using System.Runtime.InteropServices;
class Program{
[DllImport("User32.dll")]
static extern bool GetWindowText(IntPtr hwnd, StringBuilder lpString, int nMaxCount);
static void Main()
{
IntPtr hwnd = GetForegroundWindow();
StringBuilder sb = new StringBuilder(256);
if (GetWindowText(hwnd, sb,256))
{
Console.WriteLine(sb.ToString());
}
}
}
###3. 获取窗口大小`GetWindowRect()` 函数返回指定窗口的矩形区域。
csharpusing System;
using System.Runtime.InteropServices;
class Program{
[DllImport("User32.dll")]
static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT {
public int Left;
public int Top;
public int Right;
public int Bottom;
}
static void Main()
{
IntPtr hwnd = GetForegroundWindow();
RECT rect;
if (GetWindowRect(hwnd, out rect))
{
Console.WriteLine($"Width: {rect.Right - rect.Left}, Height: {rect.Bottom - rect.Top}");
}
}
}
###4. 创建新窗口`CreateWindowEx()` 函数创建一个新的顶级窗口。
csharpusing System;
using System.Runtime.InteropServices;
class Program{
[DllImport("User32.dll")]
static extern IntPtr CreateWindowEx(
uint dwExStyle,
string lpClassName,
string lpWindowName,
uint style,
int x,
int y,
int nWidth,
int nHeight,
IntPtr hWndParent,
IntPtr hMenu,
IntPtr hInstance,
IntPtr lpParam );
static void Main()
{
IntPtr hwnd = CreateWindowEx(
0, // dwExStyle "STATIC", // lpClassName "Hello, World!", // lpWindowName0x00000000, // style100, // x100, // y200, // nWidth50, // nHeight IntPtr.Zero, // hWndParent IntPtr.Zero, // hMenu Marshal.GetHINSTANCE(typeof(Program)), // hInstance IntPtr.Zero // lpParam );
Console.WriteLine(hwnd);
}
}
###5. 显示窗口`ShowWindow()` 函数显示指定窗口。
csharpusing System;
using System.Runtime.InteropServices;
class Program{
[DllImport("User32.dll")]
static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
static void Main()
{
IntPtr hwnd = GetForegroundWindow();
ShowWindow(hwnd,9); // SW_SHOW }
}
这些示例展示了如何使用 `User32.dll` 的函数在 C# 中进行窗口操作。

