Intercept data before keyboard buffer?

Can anyone tell me how to intercept scan codes before they reach the
keyboard buffer? I know how to read the scan codes from the buffer, but my
program gets stuck in a loop when I write to the buffer because it starts
reading and writing the same key over and over. Any help would be appreciated,
thanks. TP6