The simple answer is: Before "going public", 100% of the company is owned by the company itself and usually some private shareholders (investors). When the company goes public, some of the shares that were owned by the company are sold in the IPO (Initial Public Offering), and become the first publicly traded shares of the now public company.
So your assumption that money changes hands between buyers and sellers is correct, and in this case the corporation itself is the seller and they get the money from the buyers. The price that the buyers pay for these initial shares is determined the old fashioned way.. through negotiation between the corporation, the underwriter, and the investors who are interested in buying the stock. They'll look at the financial statistics of the company and how well it has done so far, and how well they think the company will do going forward.. and settle on a price at which all the shares to be sold in the IPO have a buyer.
Once the IPO is complete, public trading is open and the initial buyers are free to trade the stock between themselves or with others.
From then on, the price is determined by supply and demand, the company no longer has any say in the price of their stock. It's not uncommon for a company to buy back its own stock if the market value of the company is lower than the company feels it should be.. thus effectively investing in their own future.. and they can also sell their own stock if they want to raise additional cash.
Keep in mind that companies do not usually sell all their shares in the IPO therefore they can sell more of themselves to the public if they need cash. That's one reason that companies continue to care about their share price after they've gone public.