The company's system has a new requirement. It is very simple, that is, the colors and fonts of signatures, dates, and texts should be different when the document is presented. This is a simple requirement. However, in practice, it took me a while, isn't it a bit difficult to think about? It is a small deviation.
The RichTextBox Control is required for this function, so I wrote a method for adding text to make it simple:
Private void AddRichTextBoxText (string strText, Color TextColor, float FontSize)
{
Int iTextLength = rBox. TextLength;
RBox. Text + = strText;
RBox. SelectionStart = iTextLength;
RBox. SelectionLength = strText. Length;
RBox. SelectionFont = new Font ("", FontSize );
RBox. SelectionColor = TextColor;
}
Complete the renewal. Enter the first text. No problem. Enter the second text, I found that the fonts and colors of the second paragraph are the same as those of the first paragraph. I looked at the agent and found nothing wrong. After a few attempts, I found that every time the text in the last paragraph is written, all the text in the previous paragraph will become the same as the first paragraph. After obtaining the code, I even began wondering if the control had a BUG.
Then, the AppendText method was found when the number of members passed through. What is the difference between this method and direct operations on the text? I don't know. With a strong mind, I changed the code:
Private void AddRichTextBoxText (string strText, Color TextColor, float FontSize)
{
Int iTextLength = rtxtReply. TextLength;
RtxtReply. AppendText (strText );
RtxtReply. SelectionStart = iTextLength;
RtxtReply. SelectionLength = strText. Length;
RtxtReply. SelectionFont = new Font ("", FontSize );
RtxtReply. SelectionColor = TextColor;
}
After successful deployment, it was found that the operation was successful. None of the original problems exist. The difference between these two methods is also hard to understand. It may be a problem in the internal control system.
When changing the text color, you can use APIs to prevent the current image of the control.
// Use win32api: SendMessage to prevent flickering during control coloring
[System. Runtime. InteropServices. DllImport ("user32")]
Private static extern int SendMessage (IntPtr hwnd, int wMsg, int wParam, IntPtr lParam );
Private const int WM_SETREDRAW = 0xB;
Private void AddRichTextBoxText (string strText, Color TextColor, float FontSize)
{
Int iTextLength = rtxtReply. TextLength;
RtxtReply. AppendText (strText );
SendMessage (base. Handle, WM_SETREDRAW, 0, IntPtr. Zero );
RtxtReply. SelectionStart = iTextLength;
RtxtReply. SelectionLength = strText. Length;
RtxtReply. SelectionFont = new Font ("", FontSize );
RtxtReply. SelectionColor = TextColor;
}