roryap roryap - 3 months ago 10
C# Question

Why is my clipboard-manipulating application behaving differently when run outside of Visual Studio?

I have a console app with an "output type" of "Windows Application" (to achieve a headless behavior, i.e. no UI, no console window). The purpose is to "clean" text in the Windows clipboard, i.e. trim all leading and trailing whitespace and remove formatting.

It works great when debugging, but when I run it from explorer, it just clears the clipboard contents.

Here's my code:

[STAThread]
internal static void Main(string[] args)
{
var currentClipboardText = System.Windows.Clipboard.GetText();

// only if the clipboard has text; leave any other content intact.
if(!string.IsNullOrEmpty(currentClipboardText))
{
currentClipboardText = currentClipboardText.Trim();
var pattern = @"[\t\r\n\v\f\u2028\u2029]"; // match vert. whitesp & tabs
currentClipboardText = Regex.Replace(currentClipboardText, pattern, " ");
System.Windows.Clipboard.SetDataObject(currentClipboardText);
}
}


Sample input with formatting in MS Word, copied to clipboard:

enter image description here

After I run the program in the dubugger (either in "debug" mode or "release" mode, makes no difference), here is the result pasted back into Word from the clipboard:

enter image description here

If I do the same excercise but run the program by double-clicking on it in Windows explorer (i.e. in the
\bin\Debug
directory), there is no text left on the clipboard to paste into Word:

enter image description here

What is the difference here? Why isn't it working outside of Visual Studio?

Answer

By default, data placed on the system Clipboard with SetDataObject is automatically cleared from the Clipboard when the application exits.

MSDN

Use System.Windows.Clipboard.SetDataObject(currentClipboardText, true); instead to keep the data in the clipboard after the application exits.

Comments