You guessed it....very carefully!
But seriously, we learned a great way to medicate from our veterinary assistant. I used to try and catch our dwarf hamsters by the scruff. Very hard because these little things are moving targets with sharp teeth. But now I do the following and it is so much better.
Gently press the hamster's head down a little to prevent it from swiveling back and biting you. Then with the other hand, get a good grip on the back scruff, not just the neck but try to grab a little of the back too. Once you have a good grip with one hand you can let go the head and medicate with the other hand.
Then hold the hammie next to yourself to calm him.
Recently, we've had the good fortune of just sticking the syringe in front of our hammie's mouth. She is so angry that she grasps it with her mouth to bite and we just squeeze the meds in. Even better!
Just remember to always be careful because these little critters are VERY DELICATE!