There are several reasons why a composer may choose a specific key for his piece:
1. As mentioned before, the composer may “hear it in his mind” in that particular key.
2. The configuration of black and white keys may feel most comfortable at certain keys (I believe this may be the reason why so many Romantic pieces are written in accidental rich keys like B major, Db major, Gb major and so on: these scales fit the hand the best).
3. However if the piece was composed in the 19th century or before, there is a very good chance that the choice was guided by the theory of affects. This theory – which was at its most popular during the Baroque – stated that each key was related to a certain emotion, or “affect”. So a Baroque composer would first of all decide on the emotion he wanted to express/elicit with his piece. Then, based on this decision he would determine the key most appropriate, as well as a rhythm pattern and a melodic motif. From there it was all pretty much formulaic. Here are the affects for Eb major (according to four different authors):
a. Cruel, rough. (M. A. Charpentier – 1690)
b. Pathetic, serious, complaining, the arch-enemy of honesty. (J. Matheson – 1713)
c. Love, sad dialogue with God, the three accidentals refer to the Holy Trinity. (Ch. Fr. D. Schubart – 1739 – 1791)
d. A special quality of light and shade, found in moods of of mingled reverence and elation. (Robert Schumann – 1810 – 1856).
In the particular case of Chopin, I tend to believe that he did not pay much attention to the theory of affects. But it was pretty much taken for granted amongst musicians, and Schumann (who was his contemporary) certainly wrote a great deal about it. So he certainly was aware of it. Beethoven on the other hand certainly used it when choosing keys for his compositions. And knowledge of the theory is mandatory for anyone interested in the correct interpretation of early Classical and Baroque music.
And by the way, pitch has risen almost a semitone since Baroque times. So Bach's Prelude in C major would have to be played in B major for us to hear it in a modern piano as Bach heard it in his harpsichord.
Best wishes,
Bernhard.