Primary WinForms APIs:
Form.AcceptButton, Form.CancelButtonForm.KeyPreviewProcessCmdKey(...)Primary Avalonia APIs:
Button.IsDefault, Button.IsCancelWindow.KeyBindings + KeyBinding/KeyGestureInputElement.KeyDownEvent) for custom fallback logic| WinForms | Avalonia |
|---|---|
AcceptButton |
Button IsDefault="True" |
CancelButton |
Button IsCancel="True" |
KeyPreview + form-level key interception |
Window.KeyBindings and routed key handlers |
ProcessCmdKey overrides |
command routing + explicit KeyDown handling only for edge cases |
WinForms C#:
AcceptButton = saveButton;
CancelButton = cancelButton;
KeyPreview = true;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.S))
{
Save();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Avalonia XAML:
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:MyApp.ViewModels"
x:Class="MyApp.Views.EditCustomerWindow"
x:DataType="vm:EditCustomerViewModel"
Width="560"
Height="360"
Title="Edit Customer">
<Window.KeyBindings>
<KeyBinding Gesture="Ctrl+S"
Command="{CompiledBinding SaveCommand}" />
</Window.KeyBindings>
<Grid RowDefinitions="*,Auto" Margin="12" RowSpacing="12">
<TextBox AcceptsReturn="True"
TextWrapping="Wrap"
Text="{CompiledBinding Notes, Mode=TwoWay}" />
<StackPanel Grid.Row="1"
Orientation="Horizontal"
HorizontalAlignment="Right"
Spacing="8">
<Button Content="Cancel"
IsCancel="True"
Command="{CompiledBinding CancelCommand}" />
<Button Content="Save"
IsDefault="True"
Command="{CompiledBinding SaveCommand}" />
</StackPanel>
</Grid>
</Window>
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
var dialog = new Window
{
Width = 560,
Height = 360,
Title = "Edit Customer"
};
dialog.KeyBindings.Add(new KeyBinding
{
Gesture = KeyGesture.Parse("Ctrl+S"),
Command = viewModel.SaveCommand
});
dialog.AddHandler(InputElement.KeyDownEvent, (_, e) =>
{
if (e.KeyModifiers == KeyModifiers.Control && e.Key == Key.S)
{
viewModel.SaveCommand.Execute(null);
e.Handled = true;
}
}, RoutingStrategies.Tunnel);
var cancel = new Button
{
Content = "Cancel",
IsCancel = true,
Command = viewModel.CancelCommand
};
var save = new Button
{
Content = "Save",
IsDefault = true,
Command = viewModel.SaveCommand
};
IsDefault/IsCancel are set on buttons inside the active Window.Window.KeyBindings for primary gestures and use routed key handlers only for exceptions.ProcessCmdKey logic is too broad.