In general, many components provide a ReadOnly property ... however, in other cases there is no obvious solution.
Components with a "ReadOnly" Property
TEdit TMemo TRichEditThis is sample code I use to change the ReadOnly status of these components
procedure TForm_PortConfiguration.Protect_Fields(ReadOnly: boolean);
var
Color : TColor;
begin
if ReadOnly then Color := clScrollBar // grey indicates readonly
else Color := clWindow; // white indicates that the value can be edited
Edit1.ReadOnly := ReadOnly;
Memo1.ReadOnly := ReadOnly;
Edit1.Color := Color;
Memo1.Color := Color;
end;
TComboBox
These commands call the Windows api directly. They will keep a user from typing a new value, but not from selecting a new value from the list.
// Set ReadOnly SendMessage(GetWindow(ComboBox1.Handle,GW_CHILD), EM_SETREADONLY, 1, 0); // Remove ReadOnly SendMessage(GetWindow(ComboBox1.Handle,GW_CHILD), EM_SETREADONLY, 0, 0);You could set Enabled false, but then
procedure TForm_abc.Protect_Fields(ReadOnly: boolean);
begin
if ReadOnly then begin
ComboBox1.Tag := Port_Barcode_UIComboBox.Items.IndexOf(ComboBox1.Text);
SendMessage(GetWindow(ComboBox1.handle, GW_Child), EM_SetReadOnly, 1, 0);
end else begin
ComboBox1.Tag := -1;
SendMessage(GetWindow(ComboBox1.handle, GW_Child), EM_SetReadOnly, 0, 0);
end;
end;
procedure TForm_abc.ReadOnly_UIComboBoxChange(Sender: TObject);
var
xx : TComboBox;
begin
// This helps to make ComboBoxes read only when tag<>-1
xx := Sender as TComboBox;
if xx.Tag <> -1 then begin
xx.ItemIndex := xx.Tag;
end;
end;