3

たとえば、単純なコンソール アプリケーションがあります。私の目的は、いくつかのレポートを生成し、メモ帳や Web ブラウザーなどの外部アプリケーションでユーザーに表示することです。

class Program
    {
        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("User32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);

        static void Main()
        {
            OpenNotepadAndInputTextInIt("Message in notepad");
            OpenHtmlFileInBrowser(@"c:\temp\test.html");
        }

        private static string GetDefaultBrowserPath()
        {
            string key = @"HTTP\shell\open\command";
            using(RegistryKey registrykey = Registry.ClassesRoot.OpenSubKey(key, false))
            {
                return ((string)registrykey.GetValue(null, null)).Split('"')[1];
            }
        }

        private static void OpenHtmlFileInBrowser(string localHtmlFilePathOnMyPc)
        {
            Process browser = Process.Start(new ProcessStartInfo(GetDefaultBrowserPath(), string.Format("file:///{0}", localHtmlFilePathOnMyPc)));
            browser.WaitForInputIdle();

        }

        private static void OpenNotepadAndInputTextInIt(string textToInputInNotepad)
        {
            Process notepad = Process.Start(new ProcessStartInfo("notepad.exe"));
            notepad.WaitForInputIdle();
            if(notepad != null)
            {
                IntPtr child = FindWindowEx(notepad.MainWindowHandle, new IntPtr(0), "Edit", null);
                SendMessage(child, 0x000C, 0, textToInputInNotepad);
            }
        }
    }

このソリューションは正常に機能しますが、ご覧のとおり、2 つの方法があります。GetDefaultBrowserPath()GetDefaultBrowserPath(string localHtmlFilePathInMyPc)。1 つ目はメッセージ文字列をメモ帳ウィンドウに直接渡しますが、2 つ目はファイルやhtmlページを作成し、この html ファイルを Web ブラウザーのパラメーターとして渡す必要があります。これは一種の遅い解決策です。文字列レポートを生成し、中間の html ファイルを作成せずに Web ブラウザーに直接渡したいと考えています。html

4

1 に答える 1

2

システムのデフォルトのブラウザアプリケーションで(アプリケーションに統合するのではなく)外部ブラウザウィンドウを開きたい場合、唯一の方法はデータURIを経由することだと思います:

data:text/html,<html><title>Hello</title><p>This%20is%20a%20test

これを URI としてブラウザーに渡します。ただし、これを行うことはお勧めしません。ユーザーにとっては予想外で、表示する一時ファイルを生成することに実際に不利益があるわけではありませんよね? さらに、URI の長さの制限にすぐにぶつかり始めるかもしれません。

ちなみに、ブラウザでファイルを開く現在の方法は、必要以上に複雑です。シェルの実行はそれ自体で正しいことを行います。レジストリからブラウザのパスを手動で取得する必要はありません。

Process.Start("file:///the/path/here")
于 2012-09-24T15:18:26.167 に答える