void IsolatedFunction()
{
cout << "Redirected string1" << endl << "Redirected string2" << endl;
}
Copy Source | Copy HTML
- public static class ConsoleOutRedirector
- {
- #region Constants
-
- private const Int32 STD_OUTPUT_HANDLE = -11;
-
- #endregion
-
- #region Externals
-
- [DllImport("Kernel32.dll")]
- extern static Boolean SetStdHandle(Int32 nStdHandle, SafeHandleZeroOrMinusOneIsInvalid handle);
- [DllImport("Kernel32.dll")]
- extern static SafeFileHandle GetStdHandle(Int32 nStdHandle);
-
- #endregion
-
- #region Variables
-
- private static AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out);
- private static client = new AnonymousPipeClientStream(PipeDirection.In, server.ClientSafePipeHandle);
- private static bool First = true;
-
- #endregion
-
- #region Methods
-
- public static String GetOutput(Action action)
- {
- Debug.Assert(action != null);
-
- using (server)
- {
- if (First)
- {
- var defaultHandle = GetStdHandle(STD_OUTPUT_HANDLE);
-
- Debug.Assert(!defaultHandle.IsInvalid);
- Debug.Assert(SetStdHandle(STD_OUTPUT_HANDLE, server.SafePipeHandle));
- try
- {
- action();
- }
- finally
- {
- Debug.Assert(SetStdHandle(STD_OUTPUT_HANDLE, defaultHandle));
- }
-
- First = false;
- }
-
- server.Flush();
- client.Flush();
-
- using (client)
- {
- using (var reader = new StreamReader(client))
- {
- using (var writer = new StringWriter())
- {
- while (reader.Peek() != -1)
- {
- writer.Write(Convert.ToChar(reader.Read()));
- }
- return writer.ToString();
- }
- }
- }
- }
- }
-
- #endregion
- }
-