Shortly after the plane parks at the gate after landing, ask a flight attendant if you can talk to the pilots, and then they will ask the pilots if you can talk to them. Before takeoff, the pilots will probably be busy preparing for the flight and therefore won't be able to talk. It doesn't hurt to try requesting to talk to them before takeoff, but after landing is the best time to make a request.
During the flight, the cockpit door is locked and you will not be allowed in. Passengers used to be able to talk to the pilots during flight, but they haven't been able to do that since 9/11.