在 C# 中,获取Textbox光标所在行内容
时间: 2024-10-05 21:01:48 浏览: 181
在 C# 中,如果你想获取 Textbox 控件中光标所在的行内容,你可以通过以下步骤:
1. 首先,你需要访问 Textbox 对象。如果你有一个名为 textBox 的 TextBox 控制器,可以像这样引用它:
```csharp
TextBox textBox = yourTextBoxReference;
```
2. 获取文本框中的所有文本:
```csharp
string allText = textBox.Text;
```
3. 确定光标的位置。在 C# 中,Text 和 CaretIndex 属性可以帮助你找到光标位置:
```csharp
int caretPosition = textBox.CaretIndex;
int lineStart = textBox.GetLineFromCharIndex(caretPosition);
int lineLength = textBox.GetLineCount();
```
`GetLineFromCharIndex` 返回的是当前光标所在的行号,`GetLineCount` 则返回总的行数。
4. 计算光标所在的行内容:
```csharp
int startOffset = (lineStart - 1) * textBox.Font.Height + textBox.ClientRectangle.Y; // 减一是因为索引从0开始
int endOffset = startOffset + textBox.Font.Height;
if (caretPosition >= lineLength * textBox.Font.Height)
endOffset += textBox.Font.Height; // 如果光标在最后一行的底部
string selectedRow = allText.Substring(startOffset, Math.Min(endOffset - startOffset, allText.Length - startOffset));
```
现在,`selectedRow` 就包含了光标所在行的内容。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)