简体   繁体   中英

How to insert a carriage return in a NSTextField with MonoMac upon pressing the return key?

After reading this question together with this accepted answer , I tried to implement the given Objective-C solution with MonoMac in C#:

- (BOOL)control:(NSControl*)control
    textView:(NSTextView*)textView
    doCommandBySelector:(SEL)commandSelector
{
    BOOL result = NO;

    if (commandSelector == @selector(insertNewline:))
    {
        // new line action:
        // always insert a line-break character and don’t cause the receiver
        // to end editing
        [textView insertNewlineIgnoringFieldEditor:self]; 
        result = YES;
    }

    return result;
}

I managed to assign a delegate to my text box and override the DoCommandBySelector method. What I did not manage is to translate the line

if (commandSelector == @selector(insertNewline:))

and the line

[textView insertNewlineIgnoringFieldEditor:self]; 

into a C# equivalent, even after doing hours of try-and-error, together with lots of those "Google searches", everyone is talking about.

So my question is:

How to translate the above two lines into a working MonoMac C# code?

OK, after another bunch of tries-and-errors, I came up with the following working solution.

This is where I assign the delegate to the text field:

textMessage.Delegate = new MyTextDel();

And this is the actual delegate definition:

private class MyTextDel : NSTextFieldDelegate
{
    public override bool DoCommandBySelector (
        NSControl control, 
        NSTextView textView, 
        Selector commandSelector)
    {
        if (commandSelector.Name == "insertNewline:") {
            textView.InsertText (new NSString (Environment.NewLine));
            return true;
        }

        return false;
    }
}

So to answer my own question, the line:

if (commandSelector == @selector(insertNewline:))         // Objective-C.

translates to:

if (commandSelector.Name == "insertNewline:")             // C#.

And the line:

[textView insertNewlineIgnoringFieldEditor:self];         // Objective-C.

translates (roughly) to:

textView.InsertText (new NSString (Environment.NewLine)); // C#.

I do hope that this is working under all circumstances, my first tests look promising.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM