|
文字列を扱うWindows API関数の使い方 | ||||||||||||
|
.NET FrameworkからWindow API関数を使用する方法です。ここでは文字列を引数にとるAPI関数の使用方法を紹介します。 |
||||||||||||
|
説明 |
||||||||||||
|
・固定長文字列
固定長文字列をアンマネージコードに渡す場合、単純に文字列を渡すだけでは呼び出し先が文字列を修正できないため適切ではありません。この場合、StringBuilderバッファを引数として渡すことで解決できます。 例えば、GetWindowText関数は、固定長文字列であり、アンマネージコードに渡して操作する必要があります。 int GetWindowText( HWND hWnd, // ウィンドウまたはコントロールのハンドル LPTSTR lpString, // テキストバッファ int nMaxCount // コピーする最大文字数 );StringBuilderの容量を超えない限り、呼び出し先は、StringBuilderを逆参照して修正できます。StringBuilderを初期化して固定長にする方法は以下のようになります。
[DllImport("user32.dll")]
private static extern int GetWindowText(
IntPtr hwnd,
StringBuilder lpString,
int nMaxCount
);
static void Main()
{
StringBuilder s=new StringBuilder(260);
GetWindowText(Handle,s,s.Capacity);
MessageBox.Show(s.ToString());
}
・構造体で使用される文字列
文字列は構造体の有効なメンバだが、StringBuilderバッファは構造体の中では無効です。文字列データ型をマーシャリングする場合のオプションは以下のとおりです。ByValTStr型は構造体の固定長文字配列に使用されます。その他の型は構造体の文字列参照に対して使用されます。いくつかの例も示します。
struct StringInfoA {
char * f1;
char f2[256];
};
↓
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
struct StringInfoA
{
[MarshalAs(UnmanagedType.LPStr)]
public string f1;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=256)]
public string f2;
}
struct StringInfoB {
char * f1;
char f2[256];
BSTR f3;
};
↓
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]
struct StringInfoB
{
[MarshalAs(UnmanagedType.LPWStr)]
public string f1;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=256)]
public string f2;
[MarshalAs(UnmanagedType.BStr)]
public string f3;
}
struct StringInfoT {
TCHAR * f1;
TCHAR f2[256];
};
↓
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
struct StringInfoA
{
[MarshalAs(UnmanagedType.LPTStr)]
public string f1;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=256)]
public string f2;
}
|
||||||||||||
|
動作環境 |
||||||||||||
|
Windows XP Professional VisualStudio.NET Enterprise Architect 日本語版(SP2) VisualStudio6.0 Enterprise Edition |
||||||||||||
|
ダウンロード |
||||||||||||
|
|