58

How can I allow selecting and copying of text from MessageBox in WPF?

ns12345
  • 3,079
  • 5
  • 41
  • 62

5 Answers5

104

If you don't need selecting text as a requirement, just use System.Windows.Forms.MessageBox. It maps to the system-default one which already allows copying its contents with Ctrl+C.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • 6
    --> Total Nitpick <-- WinForms is not WPF. This is a really great trick though. – A.R. Jan 27 '11 at 15:33
  • A.R.: It's still part of .NET and in most cases you can get away with mixing them (and it's not as if this uses any WinForms controls in WPF or similar). – Joey Jan 27 '11 at 15:45
  • 1
    This may be the best answer using a *standard* .NET "MessageBox", but I think the ideal solution (and the one that would *literally* answer the O.P.'s Q) would be a message box that works like those displayed by Visual Studio where the user can mark any part or all of the text in them as if all the text were in some borderless read-only "TextBox" on the Form with the same background color as the Form. I think Microsoft developed some custom "MessageBox" for that that they're not sharing with us in .NET. – Tom Feb 04 '16 at 00:24
27

You can just use Ctrl+C while the message box has focus, but it will give you a lot more text than just the error message.

e.g.

    MessageBox.Show("Message", "Message Title", MessageBoxButton.OK);

Would copy and paste as:

    ---------------------------
    Message Title 
    ---------------------------
    Message
    ---------------------------
    OK   
    ---------------------------
danielcooperxyz
  • 960
  • 1
  • 13
  • 28
14

I did it this way:

string msgtext = "message text";
if (MessageBox.Show(msgtext, "bla bla bla. (OK to copy)", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
  { Clipboard.SetText(msgtext); }

It works pretty good.

tomloprod
  • 7,472
  • 6
  • 48
  • 66
GadyC
  • 141
  • 1
  • 3
  • 1
    for WPF: `if (msgtext, "bla bla bla. (OK to copy)", MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.OK)` – CAD bloke Oct 23 '17 at 22:42
  • 1
    I tweaked this suggestion a little to use Yes/No. `var response = MessageBox.Show("...\r\n\r\nCopy to clipboard?", "", MessageBoxButton.YesNo);` and then `if (response == MessageBoxResult.Yes) { ClipBoard.SetText("..."); }` – Adam Prescott Dec 08 '17 at 16:27
7

If you're displaying the messagebox...

System.Windows.Forms.Clipboard.SetDataObject(messageToShowInMsgBoxString, true);

will copy the item to the clipboard.

John K.
  • 5,426
  • 1
  • 21
  • 20
2

The best approach would be to use a Window with a selectable text control, like a textbox for example. I can say from experience that this is the easiest way, and will not take much time or code changes to implement.

A.R.
  • 15,405
  • 19
  • 77
  • 123