コンテンツ

Activity

リンク

Comment

雑記に戻る

2004/02/20(金)

C#で独自ウィンドウクラス定義 、とりあえず成功

とりあえず作成までは成功しました〜。クラススタイルにCS_GLOBALCLASSを指定すればよかった模様。とりあえずサンプル。


using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class MyForm : System.Windows.Forms.Form {
    [ StructLayout( LayoutKind.Sequential )]
    struct WNDCLASSEXW {
        public int   cbSize;
        public uint   style;
        public IntPtr lpfnWndProc;
        public int    cbClsExtra;
        public int    cbWndExtra;
        public IntPtr hInstance;
        public IntPtr hIcon;
        public IntPtr hCursor;
        public IntPtr hbrBackground;
        public IntPtr lpszMenuName;
        [ MarshalAs( UnmanagedType.LPWStr )] 
        public string lpszClassName;
        public IntPtr hIconSm;
    }

    [DllImport("user32.dll")]
    static extern IntPtr RegisterClassExW( ref WNDCLASSEXW lpwcx );
    [DllImport("kernel32.dll")]
    static extern IntPtr LoadLibrary( string f );
    [DllImport("kernel32.dll")]
    static extern IntPtr GetProcAddress( IntPtr hdll, string f );

    [DllImport("user32.dll")]
    static extern IntPtr GetClassName(
        IntPtr hwnd, System.Text.StringBuilder str, int size );

    protected override CreateParams CreateParams {
        get {
            CreateParams cp = base.CreateParams;
            cp.ClassName= "MyFormClass";
            return cp;
        }
    }

    public MyForm() {
        System.Text.StringBuilder str
            = new  System.Text.StringBuilder( 64 );
        GetClassName( Handle, str, 60 );
        this.Text = "クラス名 = " + str.ToString();
    }

    [STAThread]
    static void Main() {
        const uint CS_GLOBALCLASS = 0x4000;
        WNDCLASSEXW wcl = new WNDCLASSEXW();
        wcl.cbSize = 48;
        wcl.style   = CS_GLOBALCLASS;
        wcl.lpszClassName = "MyFormClass";
        wcl.lpfnWndProc = GetProcAddress(
            LoadLibrary( "user32.dll" ),
            "DefWindowProcW" );

        RegisterClassExW( ref wcl );
        Application.Run( new MyForm() );
    }
}

とりあえず作れたというだけで一切運用していませんので思わぬ問題があるかもしれません。使用する際はそのあたりをしっかり調べてから行うようにしてください。プロシージャにDefWindowProcW()を使用していますが、これは .NET のウィンドウプロシージャが Unicode であるため、こちらのほうがよいであろうという判断です。9x ではDefWindowProcA()を指定しなくてはいけません。また、RegisterClassEx()周りの文字コードも Anisi 文字コードにマーシャリングする必要があります。

本当は .NET Window のプロシージャを取れればいいのですが、取得方法がいまいち分からないのでまた今度ということで。またWNDCLASSEX.hInstanceも自分のインスタンスを割り当てたほうがよいでしょう。(.NET でのインスタンスハンドルのとり方が分からないので保留)

コメントを追加

名前、コメントは必須です。HTMLタグ、実態参照文字は使うことが出来ません。クッキーは年内対応予定。URI,メールアドレスはリンクを張ります。

名前 : 
Mail : 
Web : 

goto Top

Copyright(C)方位記号

Gポイントポイ活 Amazon Yahoo 楽天

無料ホームページ 楽天モバイル[UNLIMITが今なら1円] 海外格安航空券 海外旅行保険が無料!