How to remove accelerator characters from a string?

I have a title for a GUI control, and I want to convert it to a plain text string. In particular, I want to remove accelerator metacharacters.

For example (examples accept WinForms):

  • Reset individual occurrences of the metacharacter: &YesbecomesYes
  • Convert double occurrences to single: Income && ExpensebecomesIncome & Expense

My code will know whether it relates to the syntax of Windows Forms (where the accelerator metacharacter &) or WPF (where it is _). However, this is in the internal code, so I do not want to depend on any WinForms or WPF library functions. I need to do this using the main (non-GUI) BCL builds. (And at this point, I believe that everything that works for WinForms would be trivially modified for WPF.)

I can come up with several ways to do this, but it is not clear which is the simplest.

What is the easiest way to implement this "remove metacharacters if one, de-double, if doubled"?

Update: I assumed that WinForms and WPF process them basically the same way, but it turns out they do not. WinForms will split a single metacharacter at the end of the line ( Foo&will Foo), but WPF will not ( Foo_remain Foo_). Bonus points for an answer that appeals to both.

+3
source share
1 answer

I edited (deleted) my previous answer. I think the simplest way would be this regular expression:

string input = "s&trings && stuf&f &";
input = Regex.Replace(input, "&(.)", "$1");

This handles repeating ampersands correctly, as well as the case where the ampersand is the last character.

EDIT, based on additional information:

, WinForms "&(.?)", WPF "_(.)". , , , . , , WPF WinForms. :

string StripAccelerators(string s, bool isWinForms)
{
    string pat = (isWinForms) ? "&(.?)" : "_(.)";
    return Regex.Replace(s, pat, "$1");
}

, , , Boolean . , , .

, , . , WinForms WPF.

+4

Source: https://habr.com/ru/post/1764495/


All Articles