C#RichEditBox性能极慢(加载4分钟)

C#中的RichEditBox控件(我使用VS 2005)性能不佳。 我将一个2.5 MB的RTF文件加载到对照中,带有45.000条彩色文本行,需要4分钟。 我将相同的RTF加载到Windows XP的Wordpad中的RTF控件中,并在2秒内加载。

写字板的速度比我的应用程序快120倍。

是什么原因,我该如何解决?

我下载了Wordpad的源代码( http://download.microsoft.com/download/4/0/9/40946FEC-EE5C-48C2-8750-B0F8DA1C99A8/MFC/ole/wordpad.zip.exe )并且它具有相同的function最糟糕的表现(4分钟)。 但是这个示例是Wordpad的旧版本。

因此,微软在过去几年中改进了Wordpad中缺少的任何东西。

最后我找到了解决方案:

.NET框架使用RichEdit20W类进行Richedit控件,就像旧的Wordpad一样。 但是Windows XP的Wordpad使用了微软高度改进的新RichEdit50W。

那么如何告诉.NET框架使用RichEdit50W而不是RichEdit20W呢?

这很简单:从RichTextBox派生一个类并为LoadLibary编写托管包装器。

RichEdit50W类由MsftEdit.dll创建,该文件自Windows XP SP1起可用。 我实现了对RichEdit20W的回退,因为非常罕见的情况是有人应该在没有Service Pack的情况下使用XP。

它的工作原理!

 ///  /// The framework uses by default "Richedit20W" in RICHED20.DLL. /// This needs 4 minutes to load a 2,5MB RTF file with 45000 lines. /// Richedit50W needs only 2 seconds for the same RTF document !!! ///  protected override CreateParams CreateParams { get { CreateParams i_Params = base.CreateParams; try { // Available since XP SP1 Win32.LoadLibrary("MsftEdit.dll"); // throws // Replace "RichEdit20W" with "RichEdit50W" i_Params.ClassName = "RichEdit50W"; } catch { // Windows XP without any Service Pack. } return i_Params; } } 

注意:另请参阅http://msdn.microsoft.com/en-us/library/windows/desktop/bb787873%28v=vs.85%29.aspx

 public class Win32 { [DllImport("kernel32.dll", EntryPoint="LoadLibraryW", CharSet=CharSet.Unicode, SetLastError=true)] private static extern IntPtr LoadLibraryW(string s_File); public static IntPtr LoadLibrary(string s_File) { IntPtr h_Module = LoadLibraryW(s_File); if (h_Module != IntPtr.Zero) return h_Module; int s32_Error = Marshal.GetLastWin32Error(); throw new Win32Exception(s32_Error); } }