If it's a Bluetooth Logitech keyboard, the cleanest method is to reset the pairing first. Hold the Bluetooth button for a few seconds until it blinks fast, then search for it on your PC. For the USB receiver version, make sure you're using either the Unifying or Bolt receiver depending on the model. Installing Logitech Options+ helps a LOT mine stopped randomly disconnecting after that.