2009/04/27

關於視窗的一點心得


/// how to capture window @ mouse?
// capture the window under the cursor's position
IntPtr hWnd = Win32.WindowFromPoint(Cursor.Position);
// handle
_textBoxHandle.Text = string.Format("{0}", hWnd.ToInt32().ToString());

// class
_textBoxClass.Text = this.GetClassName(hWnd);

// caption
_textBoxText.Text = this.GetWindowText(hWnd);

Win32.Rect rc = new Win32.Rect();
Win32.GetWindowRect(hWnd, ref rc);

// rect
_textBoxRect.Text = string.Format("[{0} x {1}], ({2},{3})-({4},{5})", rc.right - rc.left, rc.bottom - rc.top, rc.left, rc.top, rc.right, rc.bottom);

/// 自己的 Root Form Handler
if (hWnd == IntPtr.Zero)
{
}

/// 如何抓 window image?

// capture that window
Image image = ScreenCapturing.GetWindowCaptureAsBitmap(handle);

// fire our image read event, which the main window will display for us
this.OnImageReadyForDisplay(image);

/// 如何等候 Image 已經畫好再做事?

public event DisplayImageEventHandler ImageReadyForDisplay;
ImageReadyForDisplay += new DisplayImageEventHandler(this.DisplayImage);
if (ImageReadyForDisplay != null)
ImageReadyForDisplay(image, false, PictureBoxSizeMode.CenterImage);

/// 如何抓例外
try
{
if (this.ImageReadyForDisplay != null)
this.ImageReadyForDisplay(image, false, PictureBoxSizeMode.CenterImage);
}
catch(Exception ex)
{
Debug.WriteLine(ex);
}

public class WindowHighlighter
{
public static void Highlight(IntPtr hWnd)
{
const float penWidth = 3;
Win32.Rect rc = new Win32.Rect();
Win32.GetWindowRect(hWnd, ref rc);

IntPtr hDC = Win32.GetWindowDC(hWnd);
if (hDC != IntPtr.Zero)
{
using (Pen pen = new Pen(Color.Black, penWidth))
{
using (Graphics g = Graphics.FromHdc(hDC))
{
g.DrawRectangle(pen, 0, 0, rc.right - rc.left - (int)penWidth, rc.bottom - rc.top - (int)penWidth);
}
}
}
Win32.ReleaseDC(hWnd, hDC);
}

public static void Refresh(IntPtr hWnd)
{
Win32.InvalidateRect(hWnd, IntPtr.Zero, 1);
Win32.UpdateWindow(hWnd);
Win32.RedrawWindow(hWnd, IntPtr.Zero, IntPtr.Zero, Win32.RDW_FRAME | Win32.RDW_INVALIDATE | Win32.RDW_UPDATENOW | Win32.RDW_ALLCHILDREN);
}
}

0 意見: