2010年12月12日日曜日

書き込み練習【ブログ】

//SendMessageポインタ
[DllImport("USER32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
//SendMessage文字列
[DllImport("USER32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPTStr)] System.Text.StringBuilder buff);
//EnumChildWindows子クラス取得用
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowProc lpEnumFunc, IntPtr lParam);
//EnumChildWindows子クラス取得用
[DllImport("user32.Dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr parentHandle, Win32Callback callback, IntPtr lParam);

//-----------------------------------------
//EnumChildWindowsからのコールバック関数
//-----------------------------------------
public delegate bool Win32Callback(IntPtr hwnd, IntPtr lParam);
public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);

//-----------------------------------------
//PostMessage用定数
//-----------------------------------------
//テキスト取得
private const int WM_GETTEXT = 0xD;
//テキスト設定
private const int WM_SETTEXT = 0xC;
//取得テキストの長さ
private const int WM_GETTEXTLENGTH = 0xE;

//--------------------------------------------------------
//引数(ポインタ)の子クラスを取得
//--------------------------------------------------------
public static List<IntPtr> GetChildWindows(IntPtr parent)
{
List<IntPtr> result = new List<IntPtr>();
GCHandle listHandle = GCHandle.Alloc(result);
try
{
EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
}
finally
{
if (listHandle.IsAllocated) { listHandle.Free(); }
}
return result;
}
//見つけた子クラスハンドルを追記していく
private static bool EnumWindow(IntPtr handle, IntPtr pointer)
{
GCHandle gch = GCHandle.FromIntPtr(pointer);
List<IntPtr> list = gch.Target as List<IntPtr>;
if (list == null)
{
throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
}
list.Add(handle);
// You can modify this to check to see if you want to cancel the operation, then return a null here
return true;
}

private void button2_Click(object sender, EventArgs e)
{

List<IntPtr> list = GetChildWindows(this.Handle);
foreach (IntPtr ptr in list)
{
//取得する文字列の長さを取得
int byteLength = SendMessage(ptr, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero).ToInt32();
System.Text.StringBuilder buff = new System.Text.StringBuilder(byteLength + 1);
//文字列を取得
SendMessage(ptr, WM_GETTEXT, byteLength + 1, buff);
//----------------------------------
//文字列が[LABEL]を含んでいたら
//文字列を変形する
//----------------------------------
if (buff.ToString().ToUpper().Contains("LABEL"))
{
System.Text.StringBuilder sb = new System.Text.StringBuilder("123");
SendMessage(ptr, WM_SETTEXT, 255, sb);
this.Refresh();
}
}
}

0 件のコメント:

コメントを投稿