问题
I'm working on a school project which is a HTML Editor. Right now, I've a problem on how to make an auto indentation whenever I make a new line. The spacing of indentation would be the same as the line above it. I hope my problem clear enough.
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
richTextBox1.Text = //this part, i don't know how to make it
}
回答1:
Rather than post complete code here, I'm going to try and steer you toward the logic so that you can take it from concept to implementation. I think that will help build a more solid understanding of (a) how to approach a coding problem in general and (b) the code required to solve this problem specifically.
First, break your problem down into a set of self-contained steps...
- Find the previous line
- Figure out how many spaces/tabs that line begins with
- Append the same number of spaces/tabs to the last line
Second, understand the limitations of your approach and make sure your requirements aren't incompatible with those limitations.
- Assumption: This solution is intended for new lines added at the END of a textbox.
Then, start to figure out how to implement your logic in whatever language you are using. The first step was "Find the previous line." How do we find the previous line? How about searching backward until you hit a line terminator? Look to see if the language you're using has something to do that automatically (hint, C# does... Google "LastIndexOf" and pay attention to the "StartIndex" parameter) If not, implement it yourself.
When you break the problem down you can search sites like SO for more focused, targeted things like "How to search a string backward" rather than broad questions like the one you asked.
Good luck with your assignment, my advice to you don't focus on the code. Focus on the thought process that leads to the code and the other things will fall into place.
回答2:
You say that you have searched for this for two days. What did you search for? How to implement automatic indentation
? Well, this will probably not lead you to a solution. (EDIT: Actually, even this will give you some results...)
Try to split the problem into pieces. What steps are required for automatic indentation? Note that this is not limited to the case when the user presses the Enter key! Once you have identifed those steps, you can start individual searches for each step. This way, you will learn quite some language and framework features which will help you a lot more than a complete code solution.
As a starter, possible steps might include:
- determine when a new line/certain character is added to the text
- determine when text is pasted to the textbox
- append text to the existing text
- etc...
来源:https://stackoverflow.com/questions/20217407/auto-indent-when-a-new-line-is-made