在Delphi 2007中,在鼠标移动事件中,我尝试使用以下命令更改鼠标光标:
procedure TFr_Board_Display.PaintBox_Proxy_BoardMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if left_mouse_button_down then begin if some_condition then begin Cursor := crDrag; end else begin Cursor := crNoDrop; end; end else begin if some_other_condition then begin Cursor := crHandPoint; end else begin Cursor := crDefault; end; end; end;
例如.但是,当鼠标左键按下时,我移动鼠标,光标不会更改为crDrag或crNoDrop.执行代码(例如Cursor:= crDrag;)但光标不会改变.当鼠标左键向上,我移动鼠标时,光标没有任何问题.
(我最初尝试使用一些Drag&Drop事件和属性,但无法按照我想要的方式工作.)
编辑:澄清所需的行为和格式化的代码.
编辑:谢谢你,Gamecat,但我希望当鼠标左键关闭时光标改变,鼠标移动光标时应该在crDrag和crNoDrop之间来回切换.
如果你在OnMouseDown中设置鼠标光标并在OnMouseUp中重置它,任何工作正常:
procedure TForm4.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Cursor := crCross; end; procedure TForm4.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Cursor := crDefault; // Or you can restore a saved cursor. end;
如果希望鼠标移动时鼠标光标作出反应,请使用以下命令:
procedure TForm4.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if ssLeft in Shift then begin if X<100 then Screen.Cursor := crCross else Screen.Cursor := crHourGlass; end else Screen.Cursor := crDefault; // Or you can restore a saved cursor. end; procedure TForm4.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Screen.Cursor := crDefault; // Or you can restore a saved cursor. end;
需要MouseUp,否则如果光标悬停在控件上方,光标将不会变回.
一定要到处使用Screen.Cursor.
稍微偏离主题,但也许对你有用.
我创建了一个全局堆栈来允许嵌套的游标更改.它允许任何代码将鼠标光标设置为他们想要的内容,而不必担心他们的调用者或被调用者将其设置为什么.
例如:
procedure AskUserWhatToDo; begin PushMouseCursor(crArrow); try if MessageDlg('Abort?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then SysUtils.Abort; finally PopMouseCursor; end; end; procedure LongProcess; begin PushMouseCursor(crHourglass); try // do something if QuestionableState then AskUserWhatToDo; // do something finally PopMouseCursor; end; end;
两个程序都不必担心对方需要什么状态或离开鼠标光标.
//=============================================================== // in a universal utility module (mine is called CraftWindows.pas) function SetMouseCursor(ACursor : TCursor) : TCursor; begin Result := Screen.Cursor; Screen.Cursor := ACursor; end; var GlobalMouseCursorStack : TList = nil; procedure PushMouseCursor(ACursor : TCursor); begin if GlobalMouseCursorStack = nil then GlobalMouseCursorStack := TList.Create; GlobalMouseCursorStack.Add(Pointer(SetMouseCursor(ACursor))); end; procedure PopMouseCursor; begin if (GlobalMouseCursorStack <> nil) and (GlobalMouseCursorStack.Count > 0) then begin SetMouseCursor(TCursor(GlobalMouseCursorStack.Last)); GlobalMouseCursorStack.Delete(GlobalMouseCursorStack.Count - 1); end; end; ... finalization GlobalMouseCursorStack.Free;