做一个打字程序,r1,r2为两个richedit控件,r2与r1中的汉字相比较,用richedit的onchange中判断无法改变自身汉字的颜色,英文的可以.
源程序如下:procedure TForm1.r2Change(Sender: TObject);/r1,r2为Trichedit组件x:=r2.SelStart ;//x,y为全局变量,初始值为0
if(copy(r2.Lines.Text ,y+1,x-y)=copy(r1.Lines.Text,y+1,x-y) ) then
   begin
   r1.SelStart :=y;
   r1.SelLength :=x-y;
   r1.SelAttributes.Color:=clblue;//颜色能改变成功
   r2.SelStart :=y;
   r2.SelLength :=x-y;    
   r2.SelAttributes.Color:=clblue;//颜色不能改变?????为什么?????   r2.SelStart :=x;
   y:=x;
   end
   else begin
    r1.SelStart :=y;
    r1.SelLength :=x-y;
    r1.SelAttributes.Color:=clred;   r2.SelStart :=y;
   r2.SelLength :=x-y;      
   r2.SelAttributes.Color:=clred;
   r2.SelStart :=x; 
   y:=x;
   endend;

解决方案 »

  1.   


    换个思路吧,参考下面代码,我没有优化,只是为了实现功能 
    procedure TForm1.RichEdit1Change(Sender: TObject);
    var
      dStr:string;
      StrLength,i:Integer;
    begin
      dStr:=RichEdit1.Text;
      StrLength:=Length(dStr);
      richedit1.SelStart:=StrLength-1;
      richedit1.SelLength:=1;
      for i:=1 to StrLength do
      begin
        RichEdit1.SelStart:=i-1;
        RichEdit1.SelLength:=1;
        if RichEdit1.Text[i]=Memo1.Text[i] then
          RichEdit1.SelAttributes.Color:=clBlue
        else
          RichEdit1.SelAttributes.Color:=clRed;
      end;
      RichEdit1.SelStart:=StrLength;
    end;
      

  2.   


    优化后的代码:
    procedure TForm1.RichEdit1Change(Sender: TObject);
    var
      StrLength, i: Integer;
    begin
      with RichEdit1 do
      begin
        StrLength := Length(Text);GetPixel
        for i := StrLength downto 1 do
        begin
          SelStart := i - 1;
          SelLength := 1;
          if (SelAttributes.Color =clBlue)or(SelAttributes.Color =clRed) then
            Break;
          if Text[i] = Memo1.Text[i] then
            SelAttributes.Color := clBlue
          else
            SelAttributes.Color := clRed;
        end;
        SelStart := StrLength;
        SelAttributes.Color:=clBlack;
      end;
    end;