I've been asked about this before. I couldn't find the thread, so here goes my solution:
Code:
(vl-load-com)
;;; List of layers & their settings - this should be loaded from a DWT file instead
;;; These are just as example
;;; nth 0 = Upper Case version of layer name - so that assoc will work
;;; nth 1 = Normal layer name so it can be created using case as required
;;; nth 2 = Colour number of layer
;;; nth 3 = Linetype of layer
(setq *LayStd* '(("LAYER1" "Layer1" 1 "DASHED") ("LAYER2" "Layer2" 2 "Continuous")))
;;; Reactor callback to check if user's typed layer name as command
(defun R:CheckLayerCommand (ro ci / cmd lay nlay)
;; Replace underscores with spaces
(setq cmd (vl-string-translate "_" " " (car ci)))
(or *acad* (setq *acad* (vlax-get-acad-object)))
(or *doc* (setq *doc* (vla-get-ActiveDocument *acad*)))
(or *layers* (setq *layers* (vla-get-Layers *doc*)))
(cond
;; Check if command is the name of an existing layer
((tblsearch "LAYER" (car ci))
(setq lay (vla-Item *layers* (car ci)))
(if (= (vla-get-LayerOn lay) :vlax-false)
(vla-put-LayerOn lay :vlax-true)
)
(if (= (vla-get-Freeze lay) :vlax-true)
(vla-put-Freeze lay :vlax-false)
)
(setvar "CLAYER" (vla-get-Name lay))
)
;; Check if command is the name of an existing layer with spaces instead of _
((tblsearch "LAYER" cmd)
(setq lay (vla-Item *layers* cmd))
(if (= (vla-get-LayerOn lay) :vlax-false)
(vla-put-LayerOn lay :vlax-true)
)
(if (= (vla-get-Freeze lay) :vlax-true)
(vla-put-Freeze lay :vlax-false)
)
(setvar "CLAYER" (vla-get-Name lay))
)
;; Check if command is the name of an standard layer
((setq lay (assoc (strcase (car ci)) *LayStd*))
(setq nlay (vla-Add *layers* (nth 1 lay)))
(vla-put-Color nlay (nth 2 lay))
(vla-put-LineType nlay (nth 3 lay))
(setvar "CLAYER" (vla-get-Name nlay))
)
;; Check if command is the name of an standard layer with spaces instead of _
((setq lay (assoc (strcase cmd) *LayStd*))
(setq nlay (vla-Add *layers* (nth 1 lay)))
(vla-put-Color nlay (nth 2 lay))
(vla-put-LineType nlay (nth 3 lay))
(setvar "CLAYER" (vla-get-Name nlay))
)
)
(princ)
)
;; Clear reactors
(setq rlst (vlr-reactors))
(foreach item rlst
(foreach ro (cdr item)
(if (= "LayerCommand" (vlr-data ro))
(vlr-remove ro)
)
)
)
(setq rlst nil item nil ro nil)
(VLR-Reaction-Set
(VLR-Command-Reactor "LayerCommand")
:vlr-unknownCommand
'R:CheckLayerCommand
)