Page 1 of 1

[4.20 Win32] Snap mouse?

Posted: Sat Sep 13, 2008 2:13 am
by kawasaki
Hello yet again,

Another quick one, Is there a way to snap a mouse to a predefined grid on a window rect?

So for instance if the grid is 5x5 and you move the mouse over the window which contains the grid, the mouse will automatically jump 5 pixels left, right, up or down, depending on the next grid point?



Thanks,

Mike

Posted: Sat Sep 13, 2008 6:00 am
by idle
You may be able to do that with SetCursorPos_(x,y) with a call to BlockInput_(#true or #false) with either Sendinput or mouse_event to do mouse clicks.

I guess it really depends upon what your trying to achieve by having the mouse snap to a grid.

I'd probably try SetCursorPos first but I posted a tip on using hooks and SendInput and kept the mouse and keyboard routines separate.

Posted: Sat Sep 13, 2008 3:11 pm
by Fluid Byte
You don't snap the mouse, you snap the object:

Code: Select all

#GRIDSIZE = 10

Procedure WindowCallback(hWnd,uMsg,wParam,lParam)
	Select uMsg
		Case #WM_PAINT
		hdc = BeginPaint_(hwnd,ps.PAINTSTRUCT)	
		For x=0 To WindowWidth(0) Step #GRIDSIZE
			For y=0 To WindowHeight(0) Step #GRIDSIZE
				SetPixel_(hdc,x,y,0)
			Next
		Next	
		EndPaint_(hwnd,ps)
	EndSelect
	
	ProcedureReturn #PB_ProcessPureBasicEvents
EndProcedure

Procedure GagdetProc(hWnd,uMsg,wParam,lParam)
	Shared lpPrevFunc
	Static bDragging, MTX, MTY

	Select uMsg
		Case #WM_LBUTTONDOWN
		MTX = lParam & $FFFF
		MTY = lParam >> 16
		bDragging = 1

		Case #WM_MOUSEMOVE
		If bDragging
			GetCursorPos_(cpt.POINT)
			ScreenToClient_(WindowID(0),cpt)
			GetClientRect_(hWnd,crc.RECT)
			MoveWindow_(hWnd,(cpt\x - MTX) / #GRIDSIZE * #GRIDSIZE,(cpt\y - MTY) / #GRIDSIZE * #GRIDSIZE,crc\right,crc\bottom,1)
		EndIf

		Case #WM_LBUTTONUP
		bDragging = 0
	EndSelect
	
	ProcedureReturn CallWindowProc_(lpPrevFunc,hWnd,uMsg,wParam,lParam)
EndProcedure

OpenWindow(0,0,0,420,320,"void",#WS_OVERLAPPEDWINDOW | 1)
CreateGadgetList(WindowID(0))
ButtonGadget(0,10,10,120,30,"DRAG ME")

lpPrevFunc = SetWindowLong_(GadgetID(0),#GWL_WNDPROC,@GagdetProc())

SetWindowCallback(@WindowCallback())

While WaitWindowEvent() ! #PB_Event_CloseWindow : Wend

Posted: Sat Sep 13, 2008 3:17 pm
by Marco2007
@Fluid Byte: Brilliant! Something for the CodeArchiv!

Posted: Sat Sep 13, 2008 7:28 pm
by idle
Fluid Byte wrote:You don't snap the mouse, you snap the object:
:lol: Well spotted Fluid Byte, the operative word missing from the question was object.

Re: [4.20 Win32] Snap mouse?

Posted: Wed Aug 24, 2011 2:43 pm
by netmaestro
I remember seeing a good solution from Sparkie, it should serve your needs. The code is a bit old so you will have to fix WindowFromPoint_() and take out the CreateGadgetList but it still works well:

http://www.purebasic.fr/english/viewtop ... 13&t=28870

Just in case you aren't familiar with the change:

Code: Select all

hwin = ChildWindowFromPoint_(WindowID(0), WindowMouseX(0) | (WindowMouseY(0)<<32) )
fixes it.