Use a common cleanup function and stop input capturing after closing the connection to allow captured devices to accept the "Connection Failed" dialog