A simulation of the generation of Smith-Purcell (SP) radiation at microwave frequencies is performed using the two-dimensional particle-in-cell code MAGIC. The simulation supposes that a continuous, thin (but infinitely wide), monoenergetic electron beam passes over a diffraction grating, while a strong axial magnetic field constrains the electrons to essentially one-dimensional motion. The code computes the time-dependent electric and magnetic fields by solving the Maxwell equations using a finite element approach. We find that the passage of the beam excites an evanescent electromagnetic wave in the proximity of the grating, which in turn leads to bunching of the initially continuous electron beam. The frequency and wave number of the bunching are determined, and found to be close to those proposed by Brau and co-workers in recent work. This frequency is below the threshold for SP radiation. However, the bunching is sufficiently strong that higher harmonics are clearly visible in the beam current. These harmonic frequencies correspond to allowed SP radiation, and we see strong emission of such radiation at the appropriate angles in our simulation, again in agreement with Brau's predictions. We also find that at the ends of the grating, some of the evanescent wave is diffracted away from the surface, and radiation below the threshold occurs. In addition, we observe a second evanescent wave at the same frequency, but with a different wave number. The existence of this wave is also predicted by the theory, although its presence in our simulation is unexpected. Numerical estimates of the growth of the evanescent wave are also in reasonable agreement with the predictions, although the precise form of the dependence of the gain on beam current remains hard to establish.