Switching USB connections between two devices?
A simple solution is to use relays. You would need some small signal relays with a nominal coil voltage lower than ~4,4V and a switching current lower than ~500mA (have a look at the USB Specifications).
There are some nice changeover relays, which would work great for this application.
You can wire the USB power connection to the relay coils, so it would switch as soon as you plug the cabel into your PC.
Don't forget to add catching diodes!

You can use transistors as well! Here is a simple schematic how to wire a transistor as a switch:







simulate this circuit &ndash; Schematic created using CircuitLab

You will find many examples how to calculate this circuit in the internet, but you need Three-state logic! Here is an example:



Instead of Transistors you can also use some logical IC's. An AND-Gate for example switches if both inputs are true. So the first input can be used as enable and the second as data input from your keyboard.
There are lots of different logical IC's with Three-State logic, which would work fine for this application.

Since you aren't the only one who want to handle a situation like this, there are many finished IC-Solutions. Just search around for an USB-Switch on a component distributor near you. Have a look at this for example:
USB 3.1 SuperSpeed 10 Gbps Switch