gpt4 book ai didi

c# - MessageBox 中的粗体文本

转载 作者:IT王子 更新时间:2023-10-29 04:19:08 26 4
gpt4 key购买 nike

如何使用 C# 在 MessageBox.Show 显示的对话框中以粗体显示文本?

最佳答案

有可能,消息框是一个常规窗口,可以像其他任何窗口一样被弄乱。然而,这样做的代码有点粗糙。向您的项目添加一个新类并粘贴此代码:

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

class BoldMessageBox : IDisposable {
private int mTries = 0;
private Form mOwner;
private Font mFont;

public BoldMessageBox(Form owner) {
mOwner = owner;
owner.BeginInvoke(new MethodInvoker(findDialog));
}

private void findDialog() {
// Enumerate windows to find the message box
if (mTries < 0) return;
EnumThreadWndProc callback = new EnumThreadWndProc(checkWindow);
if (EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero)) {
if (++mTries < 10) mOwner.BeginInvoke(new MethodInvoker(findDialog));
}
}
private bool checkWindow(IntPtr hWnd, IntPtr lp) {
// Checks if <hWnd> is a dialog
StringBuilder sb = new StringBuilder(260);
GetClassName(hWnd, sb, sb.Capacity);
if (sb.ToString() != "#32770") return true;
// Got it, get the STATIC control that displays the text
IntPtr hText = GetDlgItem(hWnd, 0xffff);
if (hText != IntPtr.Zero) {
// Get the current font
IntPtr hFont = SendMessage(hText, WM_GETFONT, IntPtr.Zero, IntPtr.Zero);
Font font = Font.FromHfont(hFont);
// And make it bold (note the size change to keep enough space!!)
mFont = new Font(font.FontFamily, font.SizeInPoints - 1f, FontStyle.Bold);
SendMessage(hText, WM_SETFONT, mFont.ToHfont(), (IntPtr)1);
}
// Done
return false;
}
public void Dispose() {
mTries = -1;
mOwner = null;
if (mFont != null) mFont.Dispose();
}

// P/Invoke declarations
private const int WM_SETFONT = 0x30;
private const int WM_GETFONT = 0x31;
private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lp);
[DllImport("user32.dll")]
private static extern bool EnumThreadWindows(int tid, EnumThreadWndProc callback, IntPtr lp);
[DllImport("kernel32.dll")]
private static extern int GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern int GetClassName(IntPtr hWnd, StringBuilder buffer, int buflen);
[DllImport("user32.dll")]
private static extern IntPtr GetDlgItem(IntPtr hWnd, int item);
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
}

然后像这样使用它:

private void button1_Click(object sender, EventArgs e) {
using (new BoldMessageBox(this)) {
MessageBox.Show("Nobugz waz here");
}
}

这种方法有一个缺陷。将字体设为粗体后,文本仍必须适合消息框为文本保留的静态控件。这要求我把字体变小。您可能需要调整此值。

关于c# - MessageBox 中的粗体文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2259027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com