2010年9月3日 星期五

在C#中確認視窗是否是全螢幕

要確認一個視窗是否是全螢幕
可以直接比對視窗的大小是否與螢幕大小相同
因為如果不是全螢幕的視窗,那至少會有一部分被工具列佔走

public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}

[DllImport("user32.dll")]
private static extern int GetWindowRect(
IntPtr hWnd, out RECT lpRect);

bool IsFullScreen(IntPtr h)
{
/// get window bound from handle
RECT b;
GetWindowRect(h, out b);

/// get screen bound from handle
Rectangle r = Screen.FromHandle(h).Bounds;

/// check if the two size is the same
if ((b.bottom - b.top) == r.Height &&
(b.right - b.left) == r.Width)
{
return true;
}

return false;
}

注意Screen這個類別是宣告在System.Windows.Forms裡面
還有Rectangle是宣告在System.Drawing裡面
所以如果是WPF的程式,則需要另外新增參考

--
參考資料
GetWindowRect Function
RECT Structure
Screen.FromHandle 方法
Detect whether active window is full screen

在C#中取得前景視窗(ForegroundWindow)的應用程式名稱

如果在寫工具類的程式,有時會需要知道目前前景的視窗
(Foreground,也就是持有Focus的視窗)
這時候可以透過Win32的API來取得相關的資訊

[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
public static extern int GetWindowThreadProcessId(
IntPtr hWnd, out int lpdwProcessId);

string GetForegroundApplicationName()
{
/// get foreground window handle
IntPtr h = GetForegroundWindow();

/// get foreground process from handle
int pId;
GetWindowThreadProcessId(h, out pId);
Process p = Process.GetProcessById(pId);

return p.ProcessName;
}

--
參考資料
GetForegroundWindow Function
GetWindowThreadProcessId Function
Process.GetProcessById 方法 (Int32)