109,878
社区成员




public Form1()
{
InitializeComponent();
//初始化
this.richTextBox1.Text = "起始行\r\n第二行\r\n第三行\r\n第四行\r\n第五行\r\n第六行\r\n第七行";
}
private void button1_Click(object sender, EventArgs e)
{
//**********************
//寫在前面
//Form中添加richTextBox1,richTextBox2,textBox1三個控件
//剪貼,可以用select(int 選取字符開始位置,int 選取字符的長度)
//**********************
//清空
this.richTextBox2.ResetText();
if (this.textBox1.Text.Trim() == "")
{
MessageBox.Show("請輸入一個整數");
return;
}
//可以寫個判斷方法
try
{
Convert.ToInt32(this.textBox1.Text.Trim());
}
catch (Exception)
{
MessageBox.Show("請輸入一個整數");
return;
}
int n = Convert.ToInt32(this.textBox1.Text.Trim());
//設置讀取的開始行,0為第一行
int startRow = 0;
//richTextBox1文本總行數
int totalRow = this.richTextBox1.Lines.Length;
int[] strLineLen = new int[totalRow];
if (totalRow > 0)
{
for (int i = 0; i < totalRow; i++)
{
strLineLen[i] = this.richTextBox1.Lines[i].Length;
}
}
if (startRow > totalRow)
{
MessageBox.Show("richTextBox中取不到此行");
return;
}
if (startRow + n < totalRow)
{
//獲取字符長度
int strTotalLen = 0;
for (int i = startRow; i < startRow + n; i++)
{
string s = "";
s = this.richTextBox1.Lines[i].ToString();
strTotalLen = strTotalLen + s.Length + 1;
}
//獲取開始字符位置
int startStrIndex = 0;
for (int i = 0; i < startRow; i++)
{
startStrIndex = startStrIndex + strLineLen[i] + 2;//2="\r\n".string.length;
}
if (startStrIndex > 1)
{
//選中richTextBox1指定行
richTextBox1.Select(startStrIndex - 1, strTotalLen);//因為是從0開始算,要減一
//剪貼至richTextBox2中
richTextBox1.Cut();
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
richTextBox2.Paste();
}
}
else
{
//起始行為0的情況
//選中richTextBox1指定行
richTextBox1.Select(startStrIndex, strTotalLen);//起始行為0
//剪貼至richTextBox2中
richTextBox1.Cut();
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
richTextBox2.Paste();
}
}
}
else
{
//獲取字符長度
int strTotalLen = 0;
for (int i = startRow; i < totalRow; i++)
{
string s = "";
s = this.richTextBox1.Lines[i].ToString();
if (i == totalRow - 1)
{
strTotalLen = strTotalLen + s.Length;//最後一行不需要加了
}
else
{
strTotalLen = strTotalLen + s.Length + 1;
}
}
//獲取開始字符位置
int startStrIndex = 0;
for (int i = 0; i < startRow; i++)
{
startStrIndex = startStrIndex + strLineLen[i] + 2;//2="\r\n".string.length;
}
if (startStrIndex > 1)
{
//選中richTextBox1指定行
richTextBox1.Select(startStrIndex - 1, strTotalLen);//因為是從0開始算,要減一
//剪貼至richTextBox2中
richTextBox1.Cut();
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
richTextBox2.Paste();
}
}
else
{
//起始行為0的情況
//選中richTextBox1指定行
richTextBox1.Select(startStrIndex, strTotalLen);//起始行為0
//剪貼至richTextBox2中
richTextBox1.Cut();
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
richTextBox2.Paste();
}
}
}
}