动态改变系统自带的字体对话框的显示位置

时间:2022-06-30 10:48:13

一个代码实例, 讲述如何改变系统对话框的显示位置

 

定义要重写的通用对话框挂钩过程,以便向通用对话框添加特定功能。在这边是的特定功能就是设置对话框的位置

 

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

class Form1 : Form
{
    Form1()
    {
        Button btn = new Button();
        btn.Parent = this;
        btn.Text = "Font";
        btn.Left = 20;
        btn.Top = 20;
       
        btn.Click += delegate { new MyFontDialog(400, 80).ShowDialog(); };
    }

    [STAThread]
    static void Main()
    {
        Application.Run(new Form1());
    }
}

class MyFontDialog : FontDialog
{
    const int WM_INITDIALOG = 0x0110;
    const int SWP_NOSIZE = 0x0001;
    const int SWP_NOZORDER = 0x0004;
   
    [DllImport("user32.dll")]
    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
    {
        SetWindowPos(hWnd, (IntPtr)0, Left, Top, 0, 0, SWP_NOSIZE | SWP_NOZORDER);

        //下面一句必写
        return base.HookProc(hWnd, msg, wParam, lParam);
    }

    // 窗口的位置
    int Left, Top;

    public MyFontDialog(int x, int y)
    {
        Left = x;
        Top = y;
    }
}