I was at the gate when the bell rang (and ran into school).
I was at the gate while the bell rang (but she didn't arrive).
"when" is a specific point in time and and "while" has some duration.
I'd say it's perfectly acceptable to say "It happened when I was at school" or "It happened while I was at school" but they are not the quite the same. The first tells you something else about the time of a specific event i.e. you were at school at the time it occurred. The second locates the event within the time you spent at school.
- For Teachers