90

メッセージを表示するためのメッセージボックスを表示するWindowsフォームアプリケーションVS2010C#があります。

私は大丈夫なボタンを持っていますが、彼らが立ち去ったら、タイムアウトして、たとえば5秒後にメッセージボックスを閉じ、メッセージボックスを自動的に閉じます。

カスタムMessageBox(Formから継承)または別のレポーターFormsがありますが、Formである必要はありません。

それについての提案やサンプルはありますか?

更新しました:

WPFの場合
C#でメッセージボックスを自動的に閉じる

カスタムメッセージボックス(フォーム継承を使用)
http://www.codeproject.com/Articles/17253/A-Custom-Message-Box

http://www.codeproject.com/Articles/327212/Custom-Message-Box-in-VC

http://tutplusplus.blogspot.com.es/2010/07/c-tutorial-create-your-own-custom.html

http://medmondson2011.wordpress.com/2010/04/07/easy-to-use-custom-c-message-box-with-a-configurable-checkbox/

スクロール可能なメッセージ
ボックスC#のスクロール可能なメッセージボックス

例外レポーター
https://stackoverflow.com/questions/49224/good-crash-reporting-library-in-c-sharp

http://www.codeproject.com/Articles/6895/A-Reusable-Flexible-Error-Reporting-Framework

解決:

たぶん、フォームを使わずに、次の答えが良い解決策だと思います。

https://stackoverflow.com/a/14522902/206730
https://stackoverflow.com/a/14522952/206730

4

14 に答える 14

129

次のアプローチを試してください。

AutoClosingMessageBox.Show("Text", "Caption", 1000);

AutoClosingMessageBoxクラスが次のように実装された場合:

public class AutoClosingMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    AutoClosingMessageBox(string text, string caption, int timeout) {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        using(_timeoutTimer)
            MessageBox.Show(text, caption);
    }
    public static void Show(string text, string caption, int timeout) {
        new AutoClosingMessageBox(text, caption, timeout);
    }
    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

更新: ユーザーがタイムアウト前に何かを選択したときに基になるMessageBoxの戻り値を取得する場合は、このコードの次のバージョンを使用できます。

var userResult = AutoClosingMessageBox.Show("Yes or No?", "Caption", 1000, MessageBoxButtons.YesNo);
if(userResult == System.Windows.Forms.DialogResult.Yes) { 
    // do something
}
...
public class AutoClosingMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    DialogResult _result;
    DialogResult _timerResult;
    AutoClosingMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        _timerResult = timerResult;
        using(_timeoutTimer)
            _result = MessageBox.Show(text, caption, buttons);
    }
    public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        return new AutoClosingMessageBox(text, caption, timeout, buttons, timerResult)._result;
    }
    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
        _result = _timerResult;
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

さらに別のアップデート

@Jackのボタン付きのケースを確認したところ、メッセージYesNoを送信するアプローチWM_CLOSEがまったく機能しないことがわかりました。別のAutoclosingMessageBoxライブラリのコンテキストで修正
を提供します。このライブラリには再設計されたアプローチが含まれており、誰かに役立つと思います。NuGetパッケージ からも入手できます。

Install-Package AutoClosingMessageBox

リリースノート(v1.0.0.2):
-最も一般的なシナリオをサポートする新しいShow(IWin32Owner)API(#1のコンテキストで);
-MessageBoxの表示を完全に制御する新しいFactory()API。

于 2013-01-25T13:41:45.467 に答える
42

WinFormsで機能するソリューション:

var w = new Form() { Size = new Size(0, 0) };
Task.Delay(TimeSpan.FromSeconds(10))
    .ContinueWith((t) => w.Close(), TaskScheduler.FromCurrentSynchronizationContext());

MessageBox.Show(w, message, caption);

メッセージボックスを所有するフォームを閉じると、ボックスも閉じるという効果に基づいています。

Windowsフォームコントロールには、それらを作成したのと同じスレッドでアクセスする必要があるという要件があります。TaskScheduler.FromCurrentSynchronizationContext()上記のサンプルコードがUIスレッド、またはユーザーが作成したスレッドで実行されると仮定すると、を使用すると確実になります。TaskFactory.StartNewコードがスレッドプール(タイマーコールバックなど)またはタスクプール(Task.Runデフォルトパラメーターを使用して作成されたタスクなど)のスレッドで実行された場合、この例は正しく機能しません。

于 2014-10-17T05:03:44.397 に答える
18

AppActivate!

参照を少し混乱させてもかまわない場合は、Microsoft.Visualbasic,この非常に短い方法を含めて使用できます。

メッセージボックスを表示する

    (new System.Threading.Thread(CloseIt)).Start();
    MessageBox.Show("HI");

CloseIt関数:

public void CloseIt()
{
    System.Threading.Thread.Sleep(2000);
    Microsoft.VisualBasic.Interaction.AppActivate( 
         System.Diagnostics.Process.GetCurrentProcess().Id);
    System.Windows.Forms.SendKeys.SendWait(" ");
}

さあ、手を洗いに行きましょう!

于 2013-01-25T16:08:23.233 に答える
11

あなたはこれを試すことができます:

[DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

[DllImport("user32.Dll")]
static extern int PostMessage(IntPtr hWnd, UInt32 msg, int wParam, int lParam);

private const UInt32 WM_CLOSE = 0x0010;

public void ShowAutoClosingMessageBox(string message, string caption)
{
    var timer = new System.Timers.Timer(5000) { AutoReset = false };
    timer.Elapsed += delegate
    {
        IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, caption);
        if (hWnd.ToInt32() != 0) PostMessage(hWnd, WM_CLOSE, 0, 0);
    };
    timer.Enabled = true;
    MessageBox.Show(message, caption);
}
于 2013-01-25T13:38:09.980 に答える
11

System.Windows.MessageBox.Show()メソッドには、最初のパラメーターとして所有者ウィンドウを受け取るオーバーロードがあります。非表示の所有者ウィンドウを作成し、それを指定した時間後に閉じると、その子メッセージボックスも閉じます。

Window owner = CreateAutoCloseWindow(dialogTimeout);
MessageBoxResult result = MessageBox.Show(owner, ...

ここまでは順調ですね。しかし、UIスレッドがメッセージボックスによってブロックされていて、ワーカースレッドからUIコントロールにアクセスできない場合、どうすればウィンドウを閉じることができますか?答えは-WM_CLOSEウィンドウメッセージを所有者ウィンドウハンドルに送信することによって:

Window CreateAutoCloseWindow(TimeSpan timeout)
{
    Window window = new Window()
    {
        WindowStyle = WindowStyle.None,
        WindowState = System.Windows.WindowState.Maximized,
        Background =  System.Windows.Media.Brushes.Transparent, 
        AllowsTransparency = true,
        ShowInTaskbar = false,
        ShowActivated = true,
        Topmost = true
    };

    window.Show();

    IntPtr handle = new WindowInteropHelper(window).Handle;

    Task.Delay((int)timeout.TotalMilliseconds).ContinueWith(
        t => NativeMethods.SendMessage(handle, 0x10 /*WM_CLOSE*/, IntPtr.Zero, IntPtr.Zero));

    return window;
}

そして、これがSendMessageWindowsAPIメソッドのインポートです。

static class NativeMethods
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
于 2013-11-20T14:19:48.337 に答える
8

CodeProjectのRogerBは、この答えに対する最も巧妙な解決策の1つを持っており、彼は2004年にそれを実行しましたが、それでもまだ問題はありません。

基本的に、ここで彼のプロジェクトに移動し、CSファイルをダウンロードします。そのリンクが死んだ場合に備えて、ここにバックアップの要点があります。CSファイルをプロジェクトに追加するか、必要に応じてコードをコピーしてどこかに貼り付けます。

次に、あなたがしなければならないのは切り替えるだけです

DialogResult result = MessageBox.Show("Text","Title", MessageBoxButtons.CHOICE)

DialogResult result = MessageBoxEx.Show("Text","Title", MessageBoxButtons.CHOICE, timer_ms)

そして、あなたは行ってもいいです。

于 2015-12-05T03:42:21.660 に答える
2

この機能を提供するコードプロジェクトプロジェクトがここにあります。

SOや他のボードで多くのスレッドをたどると、これは通常のMessageBoxでは実行できません。

編集:

ちょっとえーと、そうですね。

タイマーを使用して、MessageBoxが表示されたら開始します。メッセージボックスがOKボタンのみをリッスンする場合(1つの可能性のみ)、OnTick-Eventを使用してESCをエミュレートします-を押してSendKeys.Send("{ESC}");からタイマーを停止します。

于 2013-01-25T13:25:57.760 に答える
2

DMitryGのコード「基礎となる戻り値を取得するMessageBox」にはバグがあるため、timerResultが実際に正しく返されることはありません(MessageBox.Show呼び出しがOnTimerElapsed完了した後に戻ります)。私の修正は以下のとおりです。

public class TimedMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    DialogResult _result;
    DialogResult _timerResult;
    bool timedOut = false;

    TimedMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None)
    {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        _timerResult = timerResult;
        using(_timeoutTimer)
            _result = MessageBox.Show(text, caption, buttons);
        if (timedOut) _result = _timerResult;
    }

    public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        return new TimedMessageBox(text, caption, timeout, buttons, timerResult)._result;
    }

    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
        timedOut = true;
    }

    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
于 2017-03-08T12:25:51.360 に答える
1

Vb.netライブラリには、このためのインタラクションクラスを使用した簡単なソリューションがあります。

void MsgPopup(string text, string title, int secs = 3)
{
    dynamic intr = Microsoft.VisualBasic.Interaction.CreateObject("WScript.Shell");
    intr.Popup(text, secs, title);
}

bool MsgPopupYesNo(string text, string title, int secs = 3)
{
    dynamic intr = Microsoft.VisualBasic.Interaction.CreateObject("WScript.Shell");
    int answer = intr.Popup(text, secs, title, (int)Microsoft.VisualBasic.Constants.vbYesNo + (int)Microsoft.VisualBasic.Constants.vbQuestion);
    return (answer == 6);
}
于 2019-07-17T12:08:53.363 に答える
1

こんな感じでした

var owner = new Form { TopMost = true };
Task.Delay(30000).ContinueWith(t => {
owner.Invoke(new Action(()=>
{
      if (!owner.IsDisposed)
      {
          owner.Close();
      }
   }));
});
var dialogRes =  MessageBox.Show(owner, msg, "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
于 2019-07-26T11:33:31.193 に答える
1

私はこの質問が8歳であることを知っていますが、この目的のためのより良い解決策がありました。それは常にそこにあり、今でもあります:MessageBoxTimeout()in User32.dll

これは、Microsoft Windowsで使用されている文書化されていない関数であり、必要な機能を正確に実行します。さまざまな言語もサポートしています。

C#インポート:

[DllImport("user32.dll", SetLastError = true)]
public static extern int MessageBoxTimeout(IntPtr hWnd, String lpText, String lpCaption, uint uType, Int16 wLanguageId, Int32 dwMilliseconds);

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetForegroundWindow();

C#での使用方法:

uint uiFlags = /*MB_OK*/ 0x00000000 | /*MB_SETFOREGROUND*/  0x00010000 | /*MB_SYSTEMMODAL*/ 0x00001000 | /*MB_ICONEXCLAMATION*/ 0x00000030;

NativeFunctions.MessageBoxTimeout(NativeFunctions.GetForegroundWindow(), $"Kitty", $"Hello", uiFlags, 0, 5000);

難なく終わらせた。

于 2021-02-11T10:50:45.607 に答える
0

user32.dllにはMessageBoxTimeout()という名前の文書化されていないAPIがありますが、WindowsXP以降が必要です。

于 2016-12-21T06:44:53.133 に答える
0

EndDialog送信する代わりに使用するWM_CLOSE

[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
于 2019-05-22T07:45:03.997 に答える
0

誰かがc++でAutoClosingMessageBoxを望んでいるなら、私はここに同等のコードを実装しましたここに要点へのリンクがあります

static intptr_t MessageBoxHookProc(int nCode, intptr_t wParam, intptr_t lParam)
{
    if (nCode < 0)
        return CallNextHookEx(hHook, nCode, wParam, lParam);

    auto msg = reinterpret_cast<CWPRETSTRUCT*>(lParam);
    auto hook = hHook;

    //Hook Messagebox on Initialization.
    if (!hookCaption.empty() && msg->message == WM_INITDIALOG)
    {
        int nLength = GetWindowTextLength(msg->hwnd);
        char* text = new char[captionLen + 1];

        GetWindowText(msg->hwnd, text, captionLen + 1);

        //If Caption window found Unhook it.
        if (hookCaption == text)
        {
            hookCaption = string("");
            SetTimer(msg->hwnd, (uintptr_t)timerID, hookTimeout, (TIMERPROC)hookTimer);
            UnhookWindowsHookEx(hHook);
            hHook = 0;
        }
    }

    return CallNextHookEx(hook, nCode, wParam, lParam);
}
于 2021-02-02T06:09:43.210 に答える